altermetax
altermetax

Reputation: 706

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.

Upvotes: 0

Views: 46

Answers (1)

Barmar
Barmar

Reputation: 781096

From the documentation:

The saveptr argument is a pointer to a char * variable that is used internally by strtok_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);
}

Upvotes: 1

Related Questions