The free () function in C does not work for me

I am trying to free memory allocated through malloc()using free().

Some of the structures that he does for free, but leave some of the ways that they are, and they also remain associated with their children. It also never frees a root (gRootPtr)for a binary tree.

I use Xcode to find out if the memory used by the binary tree has been freed, and also use the if statement.

The code I use to free memory is:

void FreeMemory(InfoDefiner *InfoCarrier)
{
    if ((*InfoCarrier) != NULL) {
        FreeMemory((&(*InfoCarrier)->left));
        FreeMemory((&(*InfoCarrier)->right));
        free((*InfoCarrier));
    }
}

The code I use to find out if memory is freed.

if (gRootPtr != NULL) {
    return 1;
}
else{
    return 0;
}
-1
source share
5 answers

Firstly, free does not change the pointer itself.

void *x = malloc(1);
free(x);
assert(x != NULL); // x will NOT return to NULL

, NULL, .

-, , , :

int *x = malloc(sizeof(int));
*x = 42;
free(x);
// The vlaue of *x is undefined; it may be 42, it may be 0,
// it may crash if you touch it, it may do something even worse!

, , , free(). , free() , ( , , , , ).

+16

, . , free(pointer) NULL. , , , C:

free(pointer);
pointer = NULL;

, .

+5

NULL. .

7.21:  Why isn't a pointer null after calling free()?
    How unsafe is it to use (assign, compare) a pointer value after
    it been freed?

A:  When you call free(), the memory pointed to by the passed
    pointer is freed, but the value of the pointer in the caller
    probably remains unchanged, because C pass-by-value semantics
    mean that called functions never permanently change the values
    of their arguments.  (See also question 4.8.)

    A pointer value which has been freed is, strictly speaking,
    invalid, and *any* use of it, even if it is not dereferenced,
    can theoretically lead to trouble, though as a quality of
    implementation issue, most implementations will probably not go
    out of their way to generate exceptions for innocuous uses of
    invalid pointers.

    References: ISO Sec. 7.10.3; Rationale Sec. 3.2.2.3.
+2

, free() , - , , , . , free() , - .

. :

  • , ( ) ( , realloc()).

  • , ,

, , ( NULL).

. free(), , , , :

void safe_free(void **p)
{                    
        if (*p != NULL) {
                free(*p);
                *p = NULL;
        }                 
}

, , - . , , ?

, .

+2

The function freetakes a pointer to the allocated memory, however, it does not set this pointer to NULL, in fact, it cannot do this (it will need to take the address of the pointer for this).

A typical use case in this scenario is:

free(myptr);
myptr = NULL;
+1
source

Source: https://habr.com/ru/post/1663006/


All Articles