Even though memory is assigned for the variable ret, when run a segmentation fault is outputted

46 Views Asked by At

Output is Segmentation fault (core dumped). The line of error is line 12 but I do not understand why that would be an issue. If ret is assigned a memory location and equal to something, why is a segmentation fault outputted?

Code is:

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

int main() {

    const char *tmp = "This string literal is arbitrary";

    char *ret;

    ret = strstr(tmp, "literal");

    strcpy(ret, "");
    if (ret)
        printf("found substring at address %p\n", ret);
    else
        printf("no substring found\n");
    
    return 0;
}
1

There are 1 best solutions below

0
paxdiablo On

It is undefined behaviour to modify string literals, and tmp points to such a literal. If you want to modify it, you need to make a copy of that literal that you are allowed to modify - strstr() doesn't do that, it simply gives you a pointer into the original literal.

Of course, if you use the form below, that particular problem disappears:

char tmp[] = "This string literal is arbitrary";

This functionally gives you a writable copy of the literal.