Vencat
Vencat

Reputation: 1622

C strcpy() copies string literals without segmentation fault

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)

Upvotes: 0

Views: 213

Answers (2)

0___________
0___________

Reputation: 67564

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.

Upvotes: 3

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

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.

Upvotes: 7

Related Questions