简体   繁体   中英

Segmentation fault in strtok_r on stack string

I'm getting a segmentation fault in strtok_r in the following piece of code and I've spent a few hours trying to figure out why. Answers on other pages say you can't modify a string literal, but (as far as I know) I'm not.

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

int main() {
    char req[256];
    //char* req = malloc(256 * sizeof(char));
    strcpy(req, "hello\r\nversion 1.0\r\n\r\n");
    char** lineSavePtr;
    char* line = strtok_r(req, "\r\n", lineSavePtr);
}

If I switch the declaration of req to the dynamic one, it works. It also works if I use strtok instead of strtok_r , so I'm guessing it might have something to do with lineSavePtr ?

Thanks a lot for any answers.

From the documentation :

The saveptr argument is a pointer to a char * variable that is used internally by s trtok_r() in order to maintain context between successive calls that parse the same string.

You've provided an uninitialized pointer, not a pointer to a char * variable. When it tries to dereference the pointer, undefined behavior occurs.

Declare the variable as char * , and pass a pointer to the variable using & .

int main() {
    char req[256];
    //char* req = malloc(256 * sizeof(char));
    strcpy(req, "hello\r\nversion 1.0\r\n\r\n");
    char* lineSavePtr;
    char* line = strtok_r(req, "\r\n", &lineSavePtr);
}

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