The crash is in strtok. The problem is you pass a pointer to a string literal as its first parameter, and string literals are usually in a read only memory, so strtok
crashes when trying to change the string.
char *strtok(char *str, const char *delim);
One way to fix it:
char fileName[] = "/home/test/segmentation/test.pgm";
printf("New name: %s",new_name(fileName));
EDIT: Answer to your question below 'EDIT'.
Just change the signature of your function to return char *
:
char *new_name(char str[])
However, it would be nice to change it a bit more. Instead of using the local static buffer (name
) it would be better to pass the buffer as a second parameter, and allocate it before calling the function, in the client code. The problem with this approach is that usually the caller doesn't know the exact length or even maximum length of the string to be produced.
Another, perhaps better, option is to allocate the buffer's memory to be returned dynamically using malloc
and return pointer to it to the caller. In this case the responsibility for releasing the buffer will be with the user code, so you should document it properly.