简体   繁体   中英

New to C, not sure why this simple program is segfaulting

#include <stdio.h>
#include <string.h>

int main(){
    char *p = "26/02/1992";


    char *day;
    char *month;
    char *year;

    const char *delimiters = "/";

    day = strtok(p, delimiters);
    month = strtok (NULL, delimiters);
    year = strtok (NULL, delimiters);

    printf("%s  %s  %s\n", day, month, year);

    return 0;
}

Hey, I am just starting with C and trying out some things. Part of a program I am trying to create involves having to delimit strings. The above code is me trying to figure out how to do that. But, I keep getting segmentation faults when trying to run this but I have no idea why. I assume it is because I have done something wrong with pointers here, any help would be great

Is it related to the way I have defined the day, month, year pointers?

strtok modifies the string as it parses it.

But you created a constant, literal string with "26/02/1992" , so it cannot be modified.
(it is a read-only piece of data built into your program).

To stop the seg-fault, you'll want to make a copy of the string in memory, where you are allowed to modify it. strdup (String Duplicate) is a good function for this, but you'll need to free the memory when you're done with it.

char *p = strdup("26/02/1992");  // Make a copy of the literal string, but a copy you can modify.

[... do all your work  ...]

free(p);  // Free up your copy of the string.

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