C: Segmentation fault (core dumped) -


this question has answer here:

im writing program class assignment in c. simulate reading , writing custom-sized direct-mapped cache, involving custom-sized main memory.

these parameters used before getting segmentation fault:

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

this code. not complete yet.

#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 cache memory mapping:\n--------------------------------------");         printf("\n1) set parameters\n2) read cache\n3) write 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;              (int i=1; < 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 */ 

three issues:

  1. these

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

    needs be

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

    because

    1. casting result of malloc (and family) not required in c
    2. you should supply number of bytes allocating malloc , not amount of struct main want allocate.
  2. you need allocate memory mainhd before using here:

    mainhd->next=mainptr; 

    something

    mainhd = malloc(sizeof *mainhd);  

    will trick!

  3. don't forget free allocated memory after use.

side note: check result of malloc see if successful.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -