Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to free an array inside a struct?

Tags:

c

memory

struct

If I have a struct:

struct Rec
{
    uint16_t vals[500];
};


Rec * prec = malloc(sizeof(Rec));
//Rec * prec = (Rec *) malloc(sizeof(Rec)); This code was my original and is incorrect.
//                                          See Below for details.

// initialize everything in vals

Will this code suffice to free all memory used?

free(prec);

Or do I have to free the array separately?

like image 946
providence Avatar asked Nov 20 '11 06:11

providence


1 Answers

This will suffice.
You did not allocate the array separately, so just freeing the allocated pointer shall suffice.

Follow the Rule:
You should only call free on address returned to you by malloc, anything else will result in Undefined Behavior.

References:
c99 Standard: 7.20.3.2 The free function

Synopsis
#include
void free(void *ptr);

Description:
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc,or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

Returns
The free function returns no value.

like image 177
Alok Save Avatar answered Sep 19 '22 21:09

Alok Save