简体   繁体   中英

strtok segmentation fault error in C

I know this question is frequently asked but none of other questions are helpful. I have a code

char *hamlet[] = {"Give every man thy ear, but few thy voice.",
        "Neither a borrower nor a lender be.",
        "For loan oft loses both itself and friend",
        "And borrowing dulls the edge of husbandry.",
        "This above all: to thine own self be true."};
    int i;
    for (i = 0; i < NUM_SENTENCES; i++) {
    int size;
    char **words = splitString(hamlet[i], &size);

and in another .c file I have

char** splitString(char theString[], int *arraySize){
int numWords = 1;
int i=0;
numWords += countSpaces(theString);
char **wordArray = malloc(numWords * sizeof(char*));

char *token;
token = strtok(theString, " ");

return wordArray;

Problem is, I always get segmentation fault when I link them and run it. I believe this is error caused by memory since first code and second code are located in different .c files. I can't really find a way to solve it

The contents of the hamlet array are all string literals. These are not modifiable and typically resided in a read-only section of memory. The strtok function modifies its argument, so that's why you get a crash.

You need to make a copy of the string you're working on using strdup . Then you can copy out the substrings.

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