简体   繁体   中英

implement split string by strtok in C - Segmentation fault (core dumped)

Here is a method to implement split string by strtok in C.

void split(char** dest, char* src, const char* del){
    char* token = strtok(src, del);
    while(token!=NULL){
       *dest++ = token;
       token = strtok(NULL, del);
    }
}

I tried to test this function by main() . The test device is asus T100(32bit OS, x64 processor) compiled by Cygwin with gcc version 4.9.2 (GCC)

int main(void){
    char* str="/storage/SD:/storage/USB1";
    const char* del=":";
    char* arr[2];
    split(arr, str, del);
    return 0;
}

The result is Segmentation fault (core dumped) , why?

The sizeof(char*) is 4bytes on this test device.

If I modify

char* str="/storage/SD:/storage/USB1";

to

char str[]="/storage/SD:/storage/USB1";

everything run as expected.

String literals in C and C++ are immutable. Any attempt to modify a string literal results in undefined behaviour. Function strtok changes the string passed to it as argument. Replace this declaration

char* str = "/storage/SD:/storage/USB1";

with

char str[] = "/storage/SD:/storage/USB1";

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

And from the description of function strtok

4 The strtok function then searches from there for a character that is contained in the current separator string. If no such character is found, the current token extends to the end of the string pointed to by s1, and subsequent searches for a token will return a null pointer. If such a character is found, it is overwritten by a null character, which terminates the current token. The strtok function saves a pointer to the following character, from which the next search for a token will start.

Take also into account that function main shall have return type int .

int main( void )

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