To my understanding string literals are stored in read-only memory and modifying it during runtime leads to a segmentation fault, but my below code compiles without a segmentation fault.
#include <string.h>
#include <stdio.h>
int main() {
char* scr = "hello";
strcpy(scr,scr);
printf("%s\n",scr);
return 0;
}
output: hello
The same thing, if I tried to copy source string to different destination string literals it throws a segmentation fault
#include <string.h>
#include <stdio.h>
int main() {
char* scr = "hello";
char* dst = "hello";
strcpy(dst,scr);
printf("%s\n",dst);
return 0;
}
output : Segmentation fault (core dumped)
according to K&R book strcpy() implementation is similar to below
void strcpy(char *s, char *t)
{
while ((*s = *t) != '\0') {
s++;
t++;
}
}
if so, I should have got a Segmentation fault for both cases.
compiler details:
gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)