Memory leak when using struct with dynamic arrays in C
Quick question that's been bugging me - I'm encountering a memory leak issue in my C program where I'm using a struct that contains a dynamically allocated array. The program compiles and runs, but when I check for memory leaks using `valgrind`, I see that the memory allocated for the array is not being freed. Here is a simplified version of my code: ```c #include <stdio.h> #include <stdlib.h> typedef struct { int *data; size_t size; } DynamicArray; DynamicArray* create_array(size_t size) { DynamicArray *arr = malloc(sizeof(DynamicArray)); if (!arr) return NULL; arr->data = malloc(size * sizeof(int)); arr->size = size; return arr; } void free_array(DynamicArray *arr) { free(arr->data); free(arr); } int main() { DynamicArray *myArray = create_array(10); // Do some operations with myArray->data... // Forgot to free the array before exiting return 0; } ``` In the `main` function, I create an instance of `DynamicArray`, but I forgot to call `free_array(myArray);` before the program ends. Valgrind reports: ``` ==12345== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==12345== at 0x4C29E0F: malloc (vg_replace_malloc.c:309) ==12345== by 0x40061B: create_array (my_program.c:8) ``` I thought that as long as I free the arrays inside the `free_array` function, I would be okay. Is there a more effective way to manage memory in this case or some practice I might be overlooking to ensure my dynamic memory is being freed properly? I'm using GCC version 11.2.0 and compiling with `-Wall -Wextra`. Any insights would be greatly appreciated! This is part of a larger application I'm building. Am I missing something obvious? Am I missing something obvious?