[ back to toc ]

Malloc and Realloc

Date: 2002/05/31 17:25

Q:
Hi, i have a problem with memory allocation

char * temp_dup[10000];
while ((fgets(word2, MAXWORDSIZE+1, fp2) != NULL) )
{
temp_dup[i] = (char *) malloc(sizeof(char)) ;
strcpy(temp_dup[i] , word2);

i++;
}

fp2 is the file pointer points to the file which contains a list of
words(say 34500 lines), 1 word per line.... sometime the word can exceed
80 char long.
i got segmentation fault while allocate memory for temp_dup. I run for a
while and have seg fault. I'm thinking of using realloc instead of
malloc..... wat is the difference between them??

ANy advice would be much appreciate.

A:
In the line:

temp_dup[i] = (char *) malloc(sizeof(char)) ;

you allocate a single byte only. You have to allocate space enough to hold
the characters in word2 and the terminating zero. Thus

temp_dup[i] = (char *) malloc(strlen(word2)+1) ;

This is the problem with your code and not using malloc or realloc.

The difference:

malloc allocates memory and returns a pointer to the allocated space

realloc allocates space, copies the content of the old memory chunk to the
start of the new space, releases the old memory space and returns a
pointer to the new memory space. This way you can enlarge an allocated
memory piece.

Regards,
Peter

[ back to toc ]