I am new to C and learning structs. I am trying to malloc
a char pointer with size 30 but it is giving a segmentation fault(core dump). I searched it on the interne
As many people have pointed out, you need to allocate memory for that str
struct, before writing the fields of it.
The best way to do so in C is:
p = malloc(sizeof *p);
This has the following advantages:
sizeof
operator to compute how much storage is needed for the value p
points at.When you then allocate the string space, you can simplify it to:
p->f = malloc(30);
Because:
sizeof (char)
is always 1, so using it like you did adds nothing, 1 * 30
is always just 30
.Last, you should always check the return value of malloc()
before using it, since it can fail and return NULL
.