In this function I am trying to malloc an array of pointers, then for each pointer malloc space for a string. It compiles, but segfaults at the highlighted line. What am I doing wrong?
Code:
int LoadWordList(char *fname, char **list)
{
FILE *fp = fopen(fname, "r");
char ch;
char string[MAX_LEN];
int linecount = 0, i, len;
if(! fp)
{
printf("Error: Unable to open wordlist file.\n");
exit(EXIT_FAILURE);
}
while((ch = fgetc(fp)) != EOF)
if(ch == '\n') linecount++;
rewind(fp);
*list = (char*)malloc(linecount+1);
for(i=0; i<linecount; i++)
{
fgets(string, MAX_LEN, fp);
len = strlen(string);
list[i] = (char*)malloc(len+1); // Segfaults here
//strcpy(list[i], string);
//printf("%s", list[i]);
}
return linecount;
}
Cheers.