0

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)

Vencat
  • 1,272
  • 11
  • 36
  • 6
    Welcome to the wonderful world of undefined behavior, which doesn't have to manifest in a segfault. – Shawn Dec 16 '18 at 06:57
  • 3
    It's entirely possible that strcpy checks to see if you're copying a string to itself and does nothing, that doesn't make it any less undefined. – Retired Ninja Dec 16 '18 at 07:03

2 Answers2

7

string literals are stored in read-only memory and modifying it during runtime leads to a segmentation fault,

No, you're mistaken. It invokes undefined behaviour, and segmentation fault is one of the many possible effects of UB.

Quoting C11, chapter §6.4.5/P7, String literals

[...] If the program attempts to modify such an array, the behavior is undefined.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
3

String literals on many systems are placed in the RO memory locations. The most popular compilers under most popular OSes do it (Windows,Linux,mac os etc). But many other (for example avr-gcc) do not.

So the segfault is not the only possible effect of this UB.

But in your case I bet that the compiler has optimized the strcpy call out as copying the the object to itself is not needed.

0___________
  • 60,014
  • 4
  • 34
  • 74