strtok causing segfault but not when step through code

别等时光非礼了梦想. 提交于 2019-11-27 09:54:19
Grijesh Chauhan

The strtok() function modifies string that you wants to parse, and replace all delimiters with \0 nul symbol.

Read: char * strtok ( char * str, const char * delimiters );

str
C string to truncate.
Notice that the contents of this string are modified and broken into smaller strings (tokens). Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.

In your code:

 strtok(dateString, " "); 
           ^
           |  is a constant string literal 

dateString points to "2011/04/16 00:00" a constant string literal, and by using strtok() your code trying to write on read-only memory - that is illegal and this caused segmentation fault.

Read this linked answer for diagram to understand: how strtok() works?

Edit:

@: char * strtok ( char * str, const char * delimiters ); In given code example, str is an array, not constant string literal. Its declaration:

char str[] ="- This, a sample string.";

Here str[] is an nul terminated array of chars, that initialized with string and its length is equals to size of the assigned string. You can change the content of str[] e.g. str[i] = 'A' is a valid operation.

Whereas in your code:

char * dateTimeString = "2011/04/16 00:00"; 

dateTimeString is pointer to string literal that is not modifiable e.g dateTimeString[i] = 'A' is an illegal operation this time.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!