Reputation:
I don't understand why the following piece of code make my programm crash. 'fp' isn't modified after doing 'fopen()'.
FILE * fp;
char * line = NULL;
int len = 0;
int read;
char filePath[100] = "";
//Quick concatenate, I should use concatain but nah.
snprintf(filePath,sizeof(filePath), "%s/%s/%s",FOLDER_MAIN, "test", "data.txt");
fp = fopen(filePath, "r");
if (fp != NULL)
{
while ((read = getline(&line, &len, fp)) != -1)
{
if(startsWith(line, "value:"))
{
removeSubstring(line, "value:");
removeSubstring(line, " ");
removeSubstring(line, "\t");
removeSubstring(line, "\n");
printf("%d\t%s\n", 0, line);
}
}
fclose(fp);
//Free line pointer, is it really needed ?
if (line)
free(line);
}
int StartsWith(const char *a, const char *b)
{
if(strncmp(a, b, strlen(b)) == 0)
return 1;
return 0;
}
void removeSubstring(char *s,const char *toremove)
{
while( s=strstr(s,toremove))
memmove(s,s+strlen(toremove),1+strlen(s+strlen(toremove)));
}
EDIT: Also, 'free(line)' make also the programm crash. I added removeSubstring and StartsWith function, I hope it helps. Anyway, I don't think it impact much on the programm, since the problem is with fp...
Upvotes: 1
Views: 105
Reputation: 26757
Your code is undefined behavior.
The prototype of getline is clear ssize_t getline(char **lineptr, size_t *n, FILE *stream);
, you must use correct type specially when you use pointer !
size_t len = 0;
ssize_t read;
The compiler should have warning you.
Upvotes: 3