Need Help with realloc

Started by
1 comment, last by ugor 19 years, 10 months ago
This is my code typedef struct { char *LastName; } Name; typedef struct { int numberOfNames; LastName *link; } ArrayOfNames; int getArray(FILE *in, ArrayOfNames *array); int getName(FILE *in, LastName *name); int copyName(FILE *in, LastName *name) { int ok = 0; char temp[75]; char *string = malloc(sizeof(char));; fgets(temp,100,in); if(temp==NULL) { return 1; } temp[strlen(temp)-2] = ''\0''; if(temp[0]==''\0'') { return -1; } strcpy(string,temp); rec->value = string; return 1; } int getArray(FILE *in, ArrayOfName *array) { int counter = 0; LastName *new_name = (LastName*)malloc(sizeof(LastName)); LastName *array_name = (LastName*)calloc(1,sizeof(LastName)); while(copyRec(in,new_name)==1) { array_name[counter].code = new_name->code; array_name[counter].value = new_name->value; counter++; array_name=(DxRec*)realloc(array_name,sizeof(DxRec)*counter); array->numberOfNames++; } array->link = array_name; return 0; } The thing that i wanna do. I want my getArray function to call my copyName function so that it can store all of the name in the array of structers. My problem is when i use realloc, it changes the memory location of my pointer(?) and the program crashes after the first function has been called two time. Does anybody know what a possible solution might be for this. I was thinking about double pointer, put the thing is i don''t really know how to use them. If anybody can help I would be grateful.
Advertisement
char *string = malloc(sizeof(char));
...
strcpy(string,temp);

are you sure?

My problem is when i use realloc, it changes the memory location of my pointer(?) and the program crashes after the first function has been called two time. Does anybody know what a possible solution might be for this.

Handles.



“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” — Brian W. Kernighan
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
In addition your memory handling is far from attractive. There''s no error handling whatsoever. Either check return values from each allocation and handle NULL values, or use new/delete and have them throw bad_alloc on failure.

Especially realloc is dangerous unless you know it. If
ptr = realloc(ptr, ...)
fails, the original ptr is leaked. Thus you need a temporary variable for value, then do the NULL check, and eventually set ptr=temp.

This topic is closed to new replies.

Advertisement