简体   繁体   中英

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);

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.

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-2025 STACKOOM.COM