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.
struct Person *who = malloc(sizeof(struct Person));
Allocates enough memory to store an object of the type Person
.
Inside an Person
object the member name
just occupies a space equivalent to size of an pointer to char
.
The above malloc
just allocates that much space, to be able to do anything meaningful with the member pointer you will have to allocate memory to it separately.
#define MAX_NAME 124
who->name = malloc(sizeof(char) * MAX_NAME);
Now the member name
points to an dynamic memory of size 124
byte on the heap and it can be used further.
Also, after your usage is done you will need to remember to free
it explicitly or you will end up with a memory leak.
free(who->name);
free(who);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With