char **getLines(FILE *pFile)
{
int nLines = 0;
size_t memRes = 0;
char **lines = malloc(memRes);
char *current = (char*) malloc(20);
while(fgets(current, 20, pFile) != NULL)
{
memRes += sizeof(char*);
lines = realloc(lines, memRes);
lines[nLines] = malloc(20);
strcpy(lines[nLines], current);
nLines++;
}
free(current);
return lines;
}
void printLines(char **lines)
{
int lineI = 0;
while(lines[lineI] != NULL)
{
printf("%s", lines[lineI]);
lineI++;
}
}
First I get the lines then I print them. The odd thing about it is that my code fails when it has read exactly 13 lines of code and then prints them. I get a segmentation fault after printing the last line. It works with 12 lines and with 14 lines perfectly.
In your printLines function, "while(lines[lineI] != NULL)"
What is happening is that lines[lineI] isn't NULL, it just hasn't been allocated at the end. So because lineI is greater than nLines, it segfaults. You have to pass nLines into the function and use that to check boundries. "while (lineI < nLines)"