简体   繁体   中英

Segmentation fault when parsing text file with using strtok_r()

I have text file with multiple lines. Like:

11111111
22222222
33333333
44444444
55555555
...

I wrote ac 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");
}

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.

I think you call to strtok_r is wrong, quote from the manual

#include

char *strtok_r(char *s1, const char *s2, char **s3);

To get the first token from s1, strtok_r() is called with s1 as its first parameter. Remaining tokens from s1 are obtained by calling strtok_r() with a null pointer for the first parameter.

The second and subsequent calls to strtok_r should have the first parameter as NULL . However, I'm not sure this is why you have the segfault.

You are also changing where buffer points to in the line

buffer = rest;

when you have read the whole file and exit the fgets line runs again, buffer no longer points to a block of memory of size size . I suspect this is causing your segfault.

Also, by modifying buffer you have no way of free ing the memory that was malloc

problem is definition of char c[]="...";

it should be char c[20]="...";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM