I want to set all the pointers pointing to a freed memory location to NULL, so that no dangling pointers or double frees are possible. Is this possible in C?
For example, I have the following structures:
struct B {
int *arr;
unsigned int len;
};
struct A {
struct B *b;
};
// Freeing and setting them to NULL:
bool test_safe_free() {
struct A *a = malloc(sizeof(struct A));
struct B *b = malloc(sizeof(struct B));
b->arr = malloc(100 * sizeof(int));
b->len = 100;
a->b = b;
safe_free_A(&a);
return a == NULL && b == NULL;
}
void safe_free_B(struct B **b_ref) {
if (*b_ref != NULL) free((*b_ref)->arr);
(*b_ref)->arr = NULL;
free(*b_ref);
*b_ref = NULL;
}
void safe_free_A(struct A **a_ref) {
// Before freeing A, freeing B:
if (*a_ref != NULL) safe_free_B(&((*a_ref)->b));
free(*a_ref);
*a_ref = NULL;
}
The test_safe_free
function returns false, because even though the variable a
is set to NULL after freeing, b
is still pointing the freed memory, because the pointer is copied (and the copy is set to NULL, while the original remains the same) when a
passed into the function.
I couldn't come up with a way, a structure to resolve this, but I'm also not sure whether what I'm trying to do is even possible.