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
  • 50,375
  • 11
  • 61
  • 80

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
  • 40,917
  • 12
  • 82
  • 102
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,071
  • 14
  • 33
  • 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