Do I have to free an array inside a struct?

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.


In their earlier answers, tekknolagi and Als are both correct. If you try executing this code snippet, it might help illuminate what is happening.

// cc -o test test.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

struct rec {
    uint16_t vals[500];
};

int main (int argc, char const *argv[])
{
    printf("struct rec is %ld bytes.\n", sizeof(struct rec));

    struct rec* rec_p = (struct rec*)malloc(sizeof(struct rec));
    free(rec_p);
}

When you execute this code, you will see:

struct rec is 1000 bytes.

You called malloc only once. That call allocated all the space described by your structure definition. The matching free likewise frees up all of this memory.


You only use free when you use malloc (or a NULL pointer)

Meaning, it will automatically be freed on exit.


If you have malloced for that, then it will suffice.

Tags:

C

Memory

Struct