0

I'm trying to understand c strings and pointers better. I was playing with strcpy, and I expected the code below to cause a segmentation fault, but to my surprise, it did not.

char a [] = "hello there";
char b [] = "yay";
strcpy(b, a);
puts(a);
puts(b);

Result:

hello there
hello there

When strcpy gets to the second "l" in "hello", shouldn't the string pointed to by b be out of memory slots? I would have thought that after the third byte, strcpy would run out of allocated memory in the b array, start writing to unallocated memory, or memory allocated to another pointer, and cause a segmentation fault.

I'd appreciate help understanding this better. Thanks!

Brionius
  • 13,858
  • 3
  • 38
  • 49
  • Undefined behavior is undefined. That's why. – Andrew Henle Mar 27 '19 at 12:23
  • So if I understand you correctly, writing outside allocated memory causes undefined behavior, which means sometimes it will cause a segmentation fault, but other weird stuff can happen too, like strcpy unexpectedly "succeeding"? – Brionius Mar 27 '19 at 12:25
  • 1
    You might like to read [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). Suppose you park your car and leave the parking brake off: the car might roll away, it might not. There are no promises from the Careless Parking Police. Suppose you sit in a reserved seat in a playhouse: its owner might demand it , might not show up, or may already be sitting in the seat, again no promises. – Weather Vane Mar 27 '19 at 12:31
  • @WeatherVane I doubt that the owner will be sitting in his reserved seat if you are already sitting in it ;-) – Jabberwocky Mar 27 '19 at 12:51
  • @Jabberwocky my point is there will be trouble (: but not in all cases. The owner may already be in it. – Weather Vane Mar 27 '19 at 12:57
  • Thanks @WeatherVane! – Brionius Mar 27 '19 at 18:18

0 Answers0