2015-10-10 5 views
0

Im пишут эту программу для назначения класса в C. Его для имитации чтения и записи в кеш-память с настраиваемым размером, с использованием основной памяти нестандартного размера.C: Ошибка сегментации (ядро сбрасывается)

Эти параметры, которые я использовал, прежде чем Segmentation fault:

Enter main memory size (words): 65536 
Enter cache size (words): 1024 
Enter block size (words/block): 16 

Это мой код. Это еще не завершено.

#include<stdio.h> 
#include<stdlib.h> 

struct cache{ 
    int tag; 
    int *block; 
}; 

struct main { 
    int value; 
    int address; 
    int word; 

    struct main *next; 
}; 

struct cache *cacheptr; 
struct main *mainHd; 

int main() { 
    int option = 0; 

    while (option != 4) { 
     printf("Main memory to Cache memory mapping:\n--------------------------------------"); 
     printf("\n1) Set parameters\n2) Read cache\n3) Write to cache\n4) Exit\n\nEnter Selection: "); 
     scanf("%d",&option); 
     printf("\n"); 

     if (option == 1) { 
      int mainMemory, cacheSize, block; 

      printf("Enter main memory size (words): "); 
      scanf("%d",&mainMemory); 

      printf("Enter cache size (words): "); 
      scanf("%d",&cacheSize); 

      printf("Enter block size (words/block): "); 
      scanf("%d",&block); 

      struct main *mainptr=(struct main *)malloc(cacheSize); 
      mainHd->next=mainptr; 

      for (int i=1; i < mainMemory; i++) { 
       mainptr->value=mainMemory-i; 
       mainptr->address=i; 
       mainptr->word=i; 

       struct main *mainnxt=(struct main *)malloc(cacheSize); 
       mainptr->next=mainnxt; 
       mainptr=mainnxt; 
      } 
     } /* end if */ 
    } /* end while */ 
} /* end main */ 
+1

не могли бы вы правильно отформатировать код в качестве первого шага (например, устранить все пустые строки, отступ от него должным образом ...), так что это не огромная проблема, чтобы прочитать его? Благодарю. –

ответ

5

три вопроса:

  1. Эти

    struct main *mainptr=(struct main *)malloc(cacheSize); 
    struct main *mainnxt=(struct main *)malloc(cacheSize); 
    

    должен быть

    struct main *mainptr = malloc(cacheSize * sizeof *mainptr); 
    struct main *mainnxt = malloc(cacheSize * sizeof *mainnxt); 
    

    потому

    1. Casting the result of malloc (and family) is not required in C
    2. Вы должны поставить число байтов для распределения в malloc, а не только количество struct main вы хотите выделить.
  2. Вам нужно выделить память для mainHd перед использованием его здесь:

    mainHd->next=mainptr; 
    

    Что-то вроде

    mainHd = malloc(sizeof *mainHd); 
    

    будет делать трюк!

  3. Не забудьте указать free выделенную память после ее использования.

Side Примечание: Проверьте результат malloc, чтобы увидеть, если она была успешной.

Смежные вопросы