user2877144 user2877144 - 1 month ago 8
C Question

strtok_s crashes program when string is of char *

I am trying to get a token from a string that is delimited by space(" "). But the following code crashes the application when the string is of char * type.

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

int main(){

char *str1 = "Hello World!"; //char str1[] works
char *token;
char *savePtr;

token = strtok_s(str1, " ", &savePtr);

printf("%s", token);

return 0;
}


I also get the following warnings:

C:\Users\Haris\Desktop\C files>gcc firstProgram.c -o firstprogram.exe
firstProgram.c: In function 'main':
firstProgram.c:10:9: warning: implicit declaration of function 'strtok_s' [-Wimplicit-function-declaration]
token = strtok_s(str1, " ", &savePtr);
^
firstProgram.c:10:7: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
token = strtok_s(str1, " ", &savePtr);

Answer

The strtok_s function modifies the thing the pointer points to, turning delimiters into zeroes. So it cannot take a pointer to a constant. But you pass it str1, which is a pointer to a string constant. When it tries to modify that string to turn the delimiters into zeroes, it tries to modify a constant. That is, of course, illegal.