jiaru zhu
jiaru zhu

Reputation: 31

Segmentation fault (core dumped) c

Here is a weird problem:

token = strtok(NULL, s);
printf(" %s\n", token);  // these two lines can read the token and print 

However!

token = strtok(NULL, s);
printf("%s\n", token); // these two lines give me a segmentation fault

Idk whats happened, because I just add a space before %s\n, and I can see the value of token.

my code:

int main() {    

    FILE *bi;

    struct _record buffer;

    const char s[2] = ",";
    char str[1000];
    const char *token;

    bi = fopen(DATABASENAME, "wb+");


    /*get strings from input, and devides it into seperate struct*/
    while(fgets(str, sizeof(str), stdin)!= NULL) {
            printf("%s\n", str); // can print string line by line
            token = strtok(str, s);
            strcpy(buffer.id, token);
            printf("%s\n", buffer.id); //can print the value in the struct
            while(token != NULL){
                token = strtok(NULL, s);
                printf("%s\n", token); // problem starts here
                /*strcpy(buffer.lname, token);  
                printf("%s\n", buffer.lname); // cant do anything with token */        
    }}

    fclose(bi);

    return 1;}

Here is the example of string I read from stdin and after parsed(I just tried to strtok the first two elements to see if it works):

<15322101,MOZNETT,JOSE,n/a,n/a,2/23/1943,MALE,824-75-8088,42 SMITH AVENUE,n/a,11706,n/a,n/a,BAYSHORE,NY,518-215-5848,n/a,n/a,n/a
<
< 15322101
< MOZNETT

Upvotes: 1

Views: 151

Answers (2)

Andr&#233;s Alcarraz
Andr&#233;s Alcarraz

Reputation: 1865

Your problem reduces to the following question What is the behavior of printing NULL with printf's %s specifier? .

In short NULL as an argument to a printf("%s") is undefined. So you need to check for NULL as suggested by @kninnug

You need to change you printf as follows:

token = strtok(NULL, s);
if (token != NULL) printf("%s\n", token); 

Or else

printf ("%s\n", token == NULL ? "" : token);

Upvotes: 1

Cihangir Akturk
Cihangir Akturk

Reputation: 41

In the first version your compiler transforms printf() into a puts() and puts does not allow null pointers, because internally invokes the strlen() to determine the lenght of the string.

In the case of the second version you add a space in front of format specifier. This makes it impossible for the compiler to call puts without appending this two string together. So it invokes the actual printf() function, which can handle NULL pointers. And your code works.

Upvotes: 2

Related Questions