I have text file with multiple lines. Like:
11111111
22222222
33333333
44444444
55555555
...
I wrote a c code to retrieve each line. My code parsed all lines and wrote them to output console succesfully. But after the last line app crashed. It returns
Program received signal SIGSEGV, Segmentation fault.
Why is that?
My C Code:
FILE *fPtr;
char file[]="/root/dd";
char *rest;
char *token;
char *buffer;
unsigned long size;
fPtr = fopen(file,"r");
fseek(fPtr, 0, SEEK_END);
size=(unsigned long)ftell(fPtr);
fseek(fPtr, 0, SEEK_SET);
buffer=(char *)malloc(size);
if(fPtr)
{
while(fgets(buffer, size, fPtr))
{
while(token = strtok_r(buffer, "\n", &rest))
{
printf("token: %s\n", token);
buffer = rest;
}
}
fclose(fPtr);
}
else
{
printf("file not open \n");
}
UPDATE
I thins problem is not related with strtok_r(). Because I changed my code:
FILE *fPtr;
char file[]="/root/dd";
char *rest;
char *token;
char *buffer;
unsigned long size;
fPtr = fopen(file,"r");
if(fPtr==NULL)
{
printf("null pointer\n");
}
fseek(fPtr, 0, SEEK_END);
size=(unsigned long)ftell(fPtr);
fseek(fPtr, 0, SEEK_SET);
buffer=(char *)malloc(size);
if(fPtr)
{
while(fgets(buffer, size, fPtr))
{
printf("buffer: %s\n", buffer);
}
fclose(fPtr);
}
else
{
printf("file not open \n");
}
And still same thing happens.