0

In my assignment I'm using structs created by my own. The questions is when freeing allocated memory should I firstly free fields of struct of it is enough to call free(ptrToStruct)?

struct Prof{
    char* first_name;
    char* second_name;
    char** trained_classes; 
    int count_of_assigned_classes;
    int max_classes_to_take;
    int count_of_trained_classes;
    int assigned_to_untrained;
};
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Ayaz Baykov
  • 9
  • 1
  • 1
  • 2
    This is why it's common to have `create` and `release` methods for each struct that's complicated like this in most C programs. That way the allocation and deallocation code exists in one place – Mgetz Apr 22 '19 at 14:44

2 Answers2

1

No. If you have pointers to heap-allocated memory inside your struct, you should free them first. The reason is that the regions your pointers inside the structure point to are located on other parts of the heap. Freeing the pointer to the structure itself would only free the memory region of the structure, not associated memory regions which pointers inside your structures point to.

BearAqua
  • 518
  • 4
  • 15
0

You need to free() each of the pointers (i.e., allocated memory pointed to by the pointers) returned by a previous malloc() calloc() or realloc() call. In other words, every pointer returned by allocator function needs to be passed to free().

Also, as once passed to free(), the memory locations are not supposed to be accessed anymore, the way to free() would be to first free the inner members (needs access to the structure pointer, like ptrToStruct->first_name), and then the pointer to the structure itself (ptrToStruct).

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261