Why the following code works:
char *p;
p="hello";
printf("%s\n",p);
While this one doesn’t:
char *p;
strcpy(p,"hello");
printf("%s\n",p);
I know that adding p=malloc(4); on the second example would make the code work, but that is exactly my question. Why malloc is needed in the second example but not in the first?
I looked for similar questions on SO but none answer this exactly.
pis a pointer. You need to make it point to something. In the first case,makes
ppoint to that string literal which is located somewhere in your program’s memory at runtime.In your second case, you didn’t make
ppoint to anything, so doing anything that looks at whereppoints to is invalid.makes
ppoint to a piece of (uninitialized) memory that can holdsome_sizechars. If you reserved enough, you can then do things likestrcpy(p, "hello")becausepdoes point to a valid memory area, so copying into the memory pointed-to bypis ok. Note thatsome_sizemust be at least as big as what you want to copy into it, including the'\0'string terminator.Note that doing:
would be invalid because
"hello"can be stored as in a read-only memory, so you can’t overwrite it.