-1

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;
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    Please do not post code/output as an image - [reasoning](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question). Copy it as formatted text into the question. – kaylum Oct 10 '22 at 00:49
  • You're asking us to debug code that we cannot see. Please provide your actual code in the form of a [mre], as required in the [help/on-topic] guidelines. Code is text, and can be copied and pasted directly into the question and formatted for readability. You'll find your experiences here will be much better if you spend some time taking the [tour] and reading the [help] pages to learn how the site works before you begin posting. – Ken White Oct 10 '22 at 00:52
  • 2
    You should not try to modify strong literals. You do and the crash is one common result of incoming undefined behaviour. – Jonathan Leffler Oct 10 '22 at 00:56
  • Inlined the code from image (and added required headers in such a way problem *is* on line 12). – paxdiablo Oct 10 '22 at 01:05
  • 1
    `strcpy(ret, "");` is trying to write in read-only memory, this is undefined behaviour. – Pablo Oct 10 '22 at 01:23

1 Answers1

2

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953