Let’s say you have-
struct Person {
char *name;
int age;
int height;
int weight;
};
If you do-
struct Person *who = malloc(sizeof(struct Person));
How would C know how much memory to allocate for name variable as this can hold a large number of data/string? I am new to C and getting confused with memory allocation.
It won’t know, You will have to allocate memory for it separately.
Allocates enough memory to store an object of the type
Person.Inside an
Personobject the membernamejust occupies a space equivalent to size of an pointer tochar.The above
mallocjust allocates that much space, to be able to do anything meaningful with the member pointer you will have to allocate memory to it separately.Now the member
namepoints to an dynamic memory of size124byte on the heap and it can be used further.Also, after your usage is done you will need to remember to
freeit explicitly or you will end up with a memory leak.