Search code examples
cpointersstrcpystring-literals

Replacing part of string with another string causes segfault


I want to do something simple but I've been banging my head on this for too long. I have a string that will always end with a specific "token". In the case below "++". I want to replace the ending token with a shorter token, let's say "#".

strstr returns either NULL or a pointer to the initial ending token. strcpy should take the pointer returned from strstr and overwrite the "++" with "#\0".

At least that's what I think it should do. Instead, I get an "assignment makes integer from pointer without a cast" warning. I have tried strcpy(*newThing, "#"); and a few other things at this point. the things that don't give errors cause seg-faults.

Is it that in this case C is taking the storage for the original string from some immutable space on the stack? Do I need to use one of the "alloc"s? I've tried that too but might have missed something.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char *thing="ssssssssssssssss++";
    char *newThing;

    newThing = strstr(thing, "++");
    strcpy(newThing, "#");
    printf("%s\n", thing);

    exit(0);
}

Solution

  • Your problem is that thing is a pointer that points to a string literal. In the old days, you could have done that, but current compilers stores string literal in non writeable memory.

    So when you execute you code you get a Access violation writing location (or equivalent message).

    Simplest way to fix that : declare an automatic array initialized with the string literal, and all is fine :

    char thing[]="ssssssssssssssss++";
    

    (an array and a pointer are not exactly the same ...)