when to free pointer in C and how to know if it is freed

free in c
how to free a pointer c++
c free pointer to pointer
how free function works in c
free memory in c
where are pointers stored in c
c memory pointer
free int c

I am new in C, trying to figure out about memory allocation in C that I kinda confused

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int a;
} struct1_t;

int main()
{
    funct1(); //init pointer
    return 1;
}


int funct2(struct1_t *ptr2struct)
{
    printf("print a is %d\n",ptr2struct->a);
    //free(ptr2struct);
    printf("value of ptr in funct2 is %p\n", ptr2struct);
    return 1; //success
}


int funct1(){

    struct1_t *ptr2struct = NULL;
    ptr2struct = malloc(sizeof(*ptr2struct));
    ptr2struct->a = 5;
    printf("value of ptr before used is %p", ptr2struct);
    if (funct2(ptr2struct) == 0) {
        goto error;
    }
    free(ptr2struct);

    printf("value of ptr in funct1 after freed is is %p\n", ptr2struct);
    return 1;

error:
    if(ptr2struct) free(ptr2struct);
    return 0;
}

I have funct 1 that calls funct 2, and after using the allocated pointer in funct1, I try to free the pointer. And I create a case where if the return value in funct2 is not 1, then try again to free the pointer.

My question is below

which practice is better, if I should free the memory in funct2 (after I pass it) or in funct1 (after I finish getting the return value of funct1) The second thing is whether this is correct to make a goto error, and error:

if(ptr2struct) free(ptr2struct); 

My third question is , how do I check if the allocated value is already freed or not? because after getting the return value, I free the pointer, but if I print it, it shows the same location with the allocated one (so not a null pointer).

1) Should I free it in the calling function or in the called function?

I try to do the free-ing in the same function that does the malloc-ing. This keeps the memory-management concerns in one place and also gives better separation of concerns, since the called function in this case can also work with pointers that have not been malloc-ed or use the same pointer twice (if you want to do that).

2) Is it correct to do a "goto error"?

Yes! By jumping to a single place at the end of the function you avoid having to duplicate the resource-releasing code. This is a common pattern and isn't that bad since the "goto" is just serving as a kind of "return" statement and isn't doing any of its really tricky and evil stuff it is more known for.

//in the middle of the function, whenever you would have a return statement
// instead do
return_value = something;
goto DONE;

//...

DONE:
    //resorce management code all in one spot
    free(stuff);
    return return_value;

C++, on the other hand, has a neat way to do this kind of resource management. Since destructors are deterministically called right before a function exits they can be used to neatly package this king of resource management. They call this technique RAII

Another way other languages have to deal with this is finally blocks.

3) Can I see if a pointer has already been freed?

Sadly, you can't. What some people do is setting the pointer variable value to NULL after freeing it. It doesn't hurt (since its old value shouldn't be used after being freed anyway) and it has the nice property that freeing a null pointer is specified to be a no-op.

However, doing so is not foolproof. Be careful about having other variables aliasing the same pointer since they will still contain the old value, that is now a dangerous dangling pointer.

Dynamic Memory Allocation, () , the object it pointed to reaches the end of its lifetime. What you could however free is the src pointer in that function. but remember: the pointer cannot hold information after the underlying memory is freed! It just points to a place in memory where it should not write or read anymore.

Calling free() on a pointer doesn't change it, only marks memory as free. Your pointer will still point to the same location which will contain the same value, but that value can now get overwritten at any time, so you should never use a pointer after it is freed. To ensure that, it is a good idea to always set the pointer to NULL after free'ing it.

Why do I have to use free on a pointer but not a normal declaration , 1) Should I free it in the calling function or in the called function? I try to do the free-ing in the same function that does the malloc-ing. This keeps  Now we don't even have the pointer to the freed memory any more, and (as long as we check to see that p is non-NULL before using it), we won't misuse any memory via the pointer p. When thinking about malloc , free , and dynamically-allocated memory in general, remember again the distinction between a pointer and what it points to.

My question is below

which practice is better, if I should free the memory in funct2 (after I pass it) or in funct1 (after I finish getting the return value of funct1)

This is an "ownership" question. Who owns the allocated memory. Typically, this has to be decided based on the design of your program. For example, the only purpose of func1() could be to only allocate memory. That is, in your implementation, func1() is the function for memory allocation and then the "calling" function uses the memory. In that case, the ownership to free the memory is with the caller of func1 and NOT with func1().

The second thing is whether this is correct to make a goto error, and error: The use of "goto" is generally frowned about. It causes mess in the code that could just be easily avoided. However, I say "generally". There are cases where goto can be quiet handy and useful. For example, in big systems, configuration of the system is a big step. Now, imagine you call a single Config() function for the system which allocates memory for its different data structures at different points in the function like

   config()
     {
       ...some config code...
       if ( a specific feature is enabled)
       {
         f1 = allocateMemory();
         level = 1;
       }
       ....some more code....
       if ( another feature is enabled)
       {
         f2 = allocateMemory();
         level = 2;
       }

       ....some more codee....
      if ( another feature is enabled)
      {
        f3 = allocateMemor();
        level =3;
      }

      /*some error happens */
       goto level_3;


     level_3: 
         free(f3);
     level_2:
         free(f2);
     level_1:
         free(f1);
}

In this case, you can use goto and elegantly free only that much memory that was allocated till the point the configuration failed.

However, suffice to say in your example goto is easily avoidable and should be avoided.

My third question is , how do I check if the allocated value is already freed or not? because after getting the return value, I free the pointer, but if I print it, it shows the same location with the allocated one (so not a null pointer).

Easy. Set the freed memory as NULL. The other advantage, apart from the one mentioned by MK, is that passing NULL pointer to free will cause a NOP i.e. no operation is performed. This will also help you avoid any double delete problems.

When should I use free() in C?, If p contains a pointer previously returned by malloc, you can call free(p); the pointer to the freed memory any more, and (as long as we check to see that p is  ptr − This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated. If a null pointer is passed as argument, no action occurs. If a null pointer is passed as argument, no action occurs.

C - What Happens To Memory After free()?, Dangling pointers can lead to exploitable double-free and access-freed-memory vulnerabilities. A simple yet effective way to eliminate dangling pointers and  How does free() function know how much memory to free given just a pointer? Following is the most common way to store size of memory so that free() knows the size of memory to be deallocated. When memory allocation is done, the actual heap space allocated is one word larger than the requested memory.

I know this is answered but, I wanted to give my input. As far as I understand, when you call a function with parameters such as here (the pointer), the parameters are pushed to the stack(FILO).


Therefore the pointer passed to the function will be automagically popped off the stack but not freeing the pointer in funct1(). Therefore you would need to free the pointer in funct1() Correct me if I am wrong.

when to free pointer in C and how to know if it is freed, I know that I can free a block of data in the heap. BUT can I free When we talk of freeing a pointer, we really mean, freeing the data. And yes  Calling free() on a pointer doesn't change it, only marks memory as free. Your pointer will still point to the same location which will contain the same value, but that value can now get overwritten at any time, so you should never use a pointer after it is freed. To ensure that, it is a good idea to always set the pointer to NULL after free'ing it.

11.2 Freeing Memory, The C library functions malloc() and free() manage blocks of bytes from the free It doesn't know if your memory allocation is for one big item, or dozens of very  No, the free releases the memory block that ptr refers to, not that it nullifies the pointer itself. The block is no longer accessible - not without causing problems, anyway - but just using free does not affect the content of the pointer; that is just a number.

MEM01-C. Store a new value in pointers immediately after free(), This lets the code that implements malloc and free to assume that everything is done correctly. The free function doesn't have to check the status of the pointer  Skip trial 1 month free. ill learn about dangling pointer in c and c++ programming language. we point to some memory location in some pointer variable but we have already freed it before

Free pointer?, on heap has been freed, BUT what happens to the memory which our pointer "​px" Yes, when you use a free(px); call, it frees the memory that was The only thing that will remove the pointer var from the stack would be if it went out of If you want to also see the effect of scope, add another pair of curly 

Comments
  • If you can allocate and free in the same function, perhaps you should just keep it on the stack.
  • @missingno : for this go to, is it correct : "if(ptr2struct) free(ptr2struct);" or I should just write " free(ptrstruct). because I think that ptr2struct is a pointer, so not a bool value, can I use this notation inside the goto if the return value is not correct? Thank you
  • @MK: Some things (like variable-length arrays before C99) still need to be malloc-ed. Even then, trying to keep allocation and deallocation near each other (conceptually - it doesn't strictly need to be in the same function) is usually better.
  • @xambo: Those two versions are equivalent. if(ptr2struct) means if(ptr2struct != NULL); and free has no effect if you pass it the null pointer, anyway. And it's a bad sign if you have to call free on a pointer that may actually be null: it suggests that you're not calling free in the right place. But if your code is such that it's really possible that the pointer is null, I'd use the version with if, just so it's obvious to someone reading the code that that's expected to be a possibility.
  • @xambo: if you only free the pointer once, in the last bit of the function, you don't need to test to see if it was freed already or something like that so just free it (also,as ruakh pointed out it shouldn't really matter in this case)
  • I know this is a C question but also setting it to 0 (zero) is good too - 0 and NULL are pretty much the same thing except for some language sematics
  • so what if in the go to i write level_3: if(f3) free(f3) . So assume that if f3 has a value, then free it. or?
  • xambo: yes that is correct though unnecessary. The idea, in the example, is that if you are at level 3, f3 would have been allocated successfully.
  • If you goto level_3, you will free all three of them. If you goto level_2, you only free f2 and f1, etc. Works like switch cases that don't have breaks where execution falls through to the next case.
  • I prefer sticking to the "UpperCase for structs" convention in order to avoif typing the struct
  • :-) that's a perfectly valid way of doing it too. Consistency is the way to go. I avoid the TitleCasing approach because that is typically used in C++ or Java; and quite often I end up writing C code that is used in either of those languages so i use the foo_t convention for typedefs or struct foo for non-type defs. Again it's personal preference and your way is definitely easier on the eyes :-).