Search code examples
carraysmemory-managementmallocfree

How to free() an array of structs allocated by malloc()?


I've been working on a project that uses structs as storage for strings. I declared a struct consists of char type members:

struct datastore1
{
    char name[50];
    char address[50];
    char email[50];
    char number[50];
    char idnum[50];
};

I'm aware that I can just do char *name, char *address... but let's say we specified it with max length of 50. Then on my function which uses the struct, I malloc'ed it with index size of 30:

struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));

Supposedly I finished copying all strings into the struct by accessing each index, How should i free the allocated memory that was used after calling malloc? I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way. Should i free each indexes individually? Please enlighten me. Thank you in advance for the feedback!


Solution

  • How should i free the allocated memory that was used after calling malloc?

    Consider below example,

    struct datastore1 *obj1 = malloc(sizeof(struct datastore1));
    free(obj1);
    

    Here obj1 is pointing to the block of memory of size same as size of datastore1 in order to free you need to send the address which is allocated by malloc.

    enter image description here

    likewise,

    struct datastore1 *obj2 = malloc(3 * sizeof(struct datastore1));
    free(obj2);
    

    obj2 is pointing to a block of contiguous memory of size 3 * sizeof(datastore1) you need to pass the base address to free

    enter image description here

    Should i free each indexes individually?

    NO, Since block of memory is allocated only once and you need to free exactly one time.

    Let me extend it further,

    struct datastore1 *obj3[3];
    for(int i=0;i<3;i++)
       obj3[i] = malloc(sizeof(struct datastore1));
    
    for(int i=0;i<3;i++)
        free(obj3[i]);
    

    Here obj3 is array of pointer and each index is pointing to different part of memory and hence need to be freed individually.

    enter image description here


    Note: For simplicity I haven't considered return value from malloc. Null check has to be done on malloc return value.