I want to allocate memory for a structure that contains an array of another structure called table . I found that when assigning pointers to functions at the end, the variables in the linkedObjects array linkedObjects corrupted, so I believe that my dynamic memory processing is incorrect.
Here's how I do it now:
typedef struct Object { void *key; struct Object *top; struct Object *next; } Object; typedef struct Table{ Object *linkedObjects; size_t size, originalSize; HashFcn hfun; PrintFcn pfun; ComparisonFcn fcomp; } Table; TableP CreateTable(size_t tableSize, HashFcn hfun, PrintFcn pfun, ComparisonFcn fcomp) { int i; struct Table *table = malloc(sizeof(table)); if (table==NULL) { ReportError(MEM_OUT); return NULL; } table->linkedObjects = NULL; table->linkedObjects = malloc(tableSize * sizeof(Object)); for(i=0;i<tableSize;i++) { table->linkedObjects[i].next = malloc( MAX_IN_LIST*sizeof(Object) ); table->linkedObjects[i].top = malloc( MAX_IN_LIST*sizeof(Object) ); table->linkedObjects[i].key = NULL; table->linkedObjects[i].top->key = NULL; table->linkedObjects[i].next->key = NULL; if (table->linkedObjects[i].next == NULL) { ReportError(MEM_OUT); return NULL; } } table->size = tableSize; table->originalSize = tableSize; table->hfun = hfun; table->pfun = pfun; table->fcomp = fcomp; return table; }
Edit: I edited the function code to reflect the answers:
TableP CreateTable(size_t tableSize, HashFcn hfun, PrintFcn pfun, ComparisonFcn fcomp) { int i; struct Table *table = malloc(sizeof(table)); if (table==NULL) { ReportError(MEM_OUT); return NULL; } table->linkedObjects = NULL; table->linkedObjects = malloc(tableSize * sizeof(Object)); if (table->linkedObjects == NULL) { ReportError(MEM_OUT); return NULL; } for(i=0;i<tableSize;i++) { table->linkedObjects[i].next = NULL; table->linkedObjects[i].top = NULL; table->linkedObjects[i].key = NULL; } table->size = tableSize; table->originalSize = tableSize; table->hfun = hfun; table->pfun = pfun; table->fcomp = fcomp;
but still, when I get to the destination at the end, table->linkedObjects[0].key , which is null and the value 0x0 , will go into the value 0x8048cc0 . This happens when this line is executed:
table->originalSize = tableSize;
Other Edit: Confirmed that this happens randomly in recent calls (not just in the line above):
table->size = tableSize; table->originalSize = tableSize; table->hfun = hfun; table->pfun = pfun; table->fcomp = fcomp;
source share