Possible Duplicate:
What is the difference between char a[] = “string” and char *p = “string”?
What is the difference between using memcpy on stack memory vs on heap memory?
The following code works on Tru64 but segfaults on LINUX
char * string2 = " ";
(void)memcpy((char *)(string2),(char *)("ALT=---,--"),(size_t)(10));
The second version works on LINUX
char * string2 = malloc(sizeof(char)*12);
(void)memcpy((char *)(string2),(char *)("ALT=---,--"),(size_t)(10));
Can someone explain the segfault on LINUX?
The first example has an Undefined Behavior. And so it might work correctly or not or show any random behavior.
Explanation:
The first example, declares a pointer
string2to a string literal. String literals are stored in Implementation defined read only memory locations. A user program is not allowed to modify this memory. Any attempt to do so results in Undefined Behavior.Reference: