How to solve the segmentation fault (core dumped) error when strtok is printed?

2

I have been investigating about this error that appears to me when I try to compile the following lines for example:

char cadena[] = "hola mundo";
char * div = " ";
char * token = strtok(cadena, div);
while (token != NULL){
    printf("%s\n", token);
    token = strtok(NULL, div);
}

and when it is executed ... it arrives at that point and the segmentation fault error appears (core dumped), I know that previously they have also dealt with the same topic, but in each one I have not been able to find a solution that allows me to use This command, what I try is in code blocks to take a string of text and divide it into tokens to verify what is entered, beforehand I appreciate your help

    
asked by Steve 31.07.2016 в 00:06
source

1 answer

2

You seem to be forgetting to include the header string.h . The compiler can not find the declaration of strtok() and in that case (perhaps surprisingly ) does not throw error but compiles the call to the function assuming an implicit declaration . This implicit declaration builds it with the arguments it finds on the first use, and with return value int . Now, in the link stage, the compiler finds the "true" strtok , which (as we know) returns a pointer. Therefore, when running the program everything will probably work (by chance, so to speak) if the pointer has the same size as a int - which depends on your architecture . If not, the pointer will be invalid and will probably fail.

You can verify this explanation (tentative), by printing the sizes sizeof(int) and sizeof(char*)

Depending on the compiler you are using, there are usually options to change the behavior, so throwing an error when you forget to include the header. In any case, it is always recommended (and much more when we have problems that we do not understand) to force the compiler to issue all warnings (...) and not to ignore them.

    
answered by 07.08.2016 в 19:16