Segfault on dynamic allocation
Hi all,
I'd like to read a file line by line then remove the carriage ret and print the modified line, here's the code:
Code:
int main (int argc, char *argv[]) {
FILE *stream;
int word=100;
char *l, *buf;
stream = fopen (argv[1], "r");
if ( (buf = (char *) calloc(word, sizeof(char *))) == NULL){
printf("error");
exit(-1);
}
while (getline(&buf, &word , stream)!=-1) {
l=strchr(buf,'\n');
if(l==NULL){
printf("error");
exit(-1);
}
*l='\0'; <------------------------SEGFAULT
printf("%s\n", buf);
}
fclose(stream);
free(buf);
return 0;
}
The program seems to work correctly but inspecting further with gdb I always get a seg fault on : *l='\0';
Do you know why please? I allocate the space with calloc and even if the space may be not enough I know that getline take care of it (by reallocating the space)
Any idea?
Thx in advance