Dongho Han
Dongho Han

Reputation: 97

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

Upvotes: 0

Views: 106

Answers (1)

dbush
dbush

Reputation: 223907

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.

Upvotes: 4

Related Questions