I have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test {
char *str;
};
int main(void)
{
struct test *p = malloc(sizeof(struct test));
p->str = "hello world";
printf("%s\n",p->str);
return 0;
}
It works fine. But when I write like this:
struct test *p = malloc(sizeof(struct test));
p->str="hello";
strcat(p->str," world");
or this:
struct test *p = malloc(sizeof(struct test));
strcat(p->str,"hello world");
I got a segmentation fault.
And I found some relevant explanation here:
You are allocating only memory for the structure itself. This includes the pointer to char, which is only 4 bytes on 32bit system, because it is part of the structure. It does NOT include memory for an unknown length of string, so if you want to have a string, you must manually allocate memory for that as well
Allocate memory for a struct with a character pointer in C
With the explanation, I know the correct code should be like this if I want to use strcat:
struct test *p = malloc(sizeof(struct test));
p->str = malloc(size);
strcat(p->str,"hello world");
So my question is why p->str = "hello world" does not need allocate memory but strcat(p->str,"hello world") needs allocate memory before use?
My compiler is "gcc (Debian 4.9.2-10) 4.9.2". My English is pretty basic, please don't mind :)