Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does malloc assigns memory to custom struct's properties?

I’ve been working on some C projects and was wondering if I create a custom structure, for example, Student, define a variable of the custom structure type, and allocate memory to it using malloc, does it also allocate memory for variables’ properties separately or are they all kept in the same space? if yes, will there be any difference if I allocate memory using malloc separately for every property?

For example:

typedef struct { 
    unsigned int ID; 
    char *first_name; 
    char *last_name;
    int num_grades; 
    float *grades;
    unsigned short int days_absent; 
    char *memo;
} Student;

int main() {

    // Declare students array
    Student *students = NULL;
    int students_size = 0;

    // Allocate memory for students array
    students = (Student *) malloc(sizeof(Student));
    
    return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That allocates enough memory for the struct, which includes enough memory for ID, first_name, etc and all padding requirements.

Note that while it allocates memory for the pointer first_name, it doesn’t allocate a buffer to hold the name. Just the pointer. If you want memory in which to store the names, you will need to allocate it.

If the struct had a char first_name[40]; field, it would be a different story. In that case, the struct would contain an array of 40 char instead of a pointer. So it would allocate enough space for an array of 40 char instead of enough for a pointer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading