Home > Enterprise >  How does free() interact with a struct made on the stack that contains an array made on the heap?
How does free() interact with a struct made on the stack that contains an array made on the heap?

Time:06-01

Say I want to create a new struct that contains image data

struct Image {
    int *pxl_arr;
    int pxl_arr_len;
    int img_wdt, img_hgt;
};

And I also had a separate function that opened an image file and copied the contents of the file into an array of integers made on the heap using malloc(), so that some other function could parse that data and use it with the struct Image

int *freadarr (char *fpath) {
    FILE *fptr;
    long len;
    int *buf;

 /* code to open file here */

    buf = (int *) malloc(len);

 /* code to read from file here */ 

    return buf;
}

Then inside of the main() function, I were to do this:

int main() {
    struct Image img;
    img.pxl_arr = freadarr(/* whatever the file path is */);
    free(img);
    return 0;
}

What would free() do with the struct Image?

EDIT: img.pxl_arr, not img->pxl_arr

CodePudding user response:

What would free() do with the struct Image?

Nothing, as you should only pass to free any pointer value returned from malloc (or calloc / realloc), or NULL. In your (slightly flawed) example, that would be the value held by the pxl_arr member of the structure.

Or maybe anything, as passing any other value is Undefined Behaviour, but your compiler should complain loudly about free(img);:

main.c:12:10: error: incompatible type for argument 1 of ‘free’
   12 |     free(img);
      |          ^~~
      |          |
      |          struct Image

Pass the pointer value to free when you are done with it:

struct Image img;
img.pxl_arr = freadarr(/* whatever the file path is */);
/* ... do stuff .. */
free(img.pxl_arr);

Note that -> is for accessing the members of a structure via a pointer. img is not a pointer, so use the . operator. See: Member access operators

CodePudding user response:

free(struct) is use to free (hehe) the memory that have been recerved to struct.

In this case you will lose the info inside struct Image, that means one Pointer and 2 Integers, if and only if the struct Image have been recerved with malloc().

  • Related