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..
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With