c - array is full of the last element in a file -


i have procedure readtokens() takes file , array , tokenizes file , puts things array when access array, full of last element. why? here readtokens() method:

void readtokens(char *filename, char** a[]) { file *fp; char *token; int count = 0;  fp = fopen(filename, "r"); if (fp == 0)     {     fprintf(stderr,"file %s not opened reading\n", filename);     exit(1);     }  token = readline(fp); while(!feof(fp))     {     a[count] = token;     ++count;     free(token);     token = readline(fp);     }  fclose(fp); } 

you should not call free(token), since still have pointer in a[count]. since you're freeing it, memory can reused, , apparently it's being used when readline() reads next line. each time read line, reuses same memory , overwrites next line. result, elements of a[] contain pointers same line.

a[count] = token doesn't make copy of token, assigns pointer.

this assumes readline() uses malloc() allocate memory line reads. if doesn't, it's worse, since must not call free() on memory wasn't allocated malloc() or calloc().

it's possible readline() using static array variable, explain why lines same. if don't want keep overwriting token, need make copy of in readtokens(). if posted definition of readline().


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

visual studio 2010 - Connect to informix database windows form application -

android - Associate same looper with different threads -