4

Yesterday I had a little trouble with a homemade "strcpy" function. It works now though but I'm a little confused!

char* a = "Hello, World!"; //Works
char b[] = "Hello, World!"; //Works also

strcpy(a, "Hello!"); //Segmentation fault
strcpy(b, "Haha!!"); //Works..

Where is the difference? Why does the char pointer cause a "Segmentation fault"?

Why does this even work? :

char* a = "Haha"; //works
a = "LOL"; //works..
Benjamin Bannier
  • 55,163
  • 11
  • 60
  • 80
  • I removed the C++ tag since this is about the C subset (and even there you wouldn't implement `strcpy` yourself). – Benjamin Bannier May 22 '13 at 13:33
  • Read this section of the C FAQ : http://c-faq.com/aryptr/aryptr2.html – Claudio May 22 '13 at 13:23
  • Read: [Difference between `char *str` and `char str[]` and how both stores in memory?](http://stackoverflow.com/questions/15177420/what-does-sizeofarray-return/15177499#15177499) – Grijesh Chauhan Oct 12 '13 at 10:54

2 Answers2

13
char* a = "Hello, World!";

gives you a pointer to a string literal. A string literal may exist in read only memory so its contents cannot be changed.

char* a = "Haha"; //works
a = "LOL"; //works..

changes the pointer a to point to a different string literal. It doesn't attempt to modify the contents of either string literal so is safe/correct.

char b[] = "Hello, World!"

declares an array on the stack and initialises it with the contents of a string literal. Stack memory is writeable so its perfectly safe to change the contents of this memory.

simonc
  • 41,632
  • 12
  • 85
  • 103
1

In your first example since you are trying to write to a read only memory pointed by a,you will get the segmentation fault.If you want to use pointers then allocate the memory on heap,use and delete it after its use. Where as b is an array of chars initialized with "Hello, World!".

In the second example you are making the pointer to point to different string literal which should be fine.

ZoomIn
  • 1,237
  • 1
  • 17
  • 35
  • I find this answer very helpful. I didn't know that the string literal is located in the read only memory. Also I found a tutorial how to use char pointers in combination with strcpy which caused a segmentation fault here and they were allocating memory and i couldn't retrace why they did it. Thanks. – Normal People Scare Me May 22 '13 at 17:59