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:
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
- casting result of
malloc
(and family) not required in c - you should supply number of bytes allocating
malloc
, not amount ofstruct main
want allocate.
- casting result of
you need allocate memory
mainhd
before using here:mainhd->next=mainptr;
something
mainhd = malloc(sizeof *mainhd);
will trick!
- don't forget
free
allocated memory after use.
side note: check result of malloc
see if successful.
Comments
Post a Comment