Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocation of memory for char array

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.

like image 615
Sajal Dutta Avatar asked Jan 31 '12 14:01

Sajal Dutta


1 Answers

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); 
like image 187
Alok Save Avatar answered Sep 26 '22 08:09

Alok Save