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;
}
It is undefined behaviour to modify string literals, and
tmppoints 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:
This functionally gives you a writable copy of the literal.