Search code examples
cdynamic-memory-allocation

if i execute this program, Im getting "Failed to Free". But Inside FREE function, it was deallocate the memory properly only


#include "stdafx.h"
#include "stdlib.h"
#include "string.h"
typedef struct
{
    int a ;
    char b;
    char c[50];
}TEST;

void *allocate(int count,int  size);
void FREE(TEST *ptr);
int _tmain(int argc, _TCHAR* argv[])
{
    TEST *test = NULL ;
    void *ptr = NULL ;
    ptr = allocate(2,sizeof(TEST));
    test = (TEST *)ptr;
    test->a = 1;
    test->b = 'A';
    strcpy(test->c,"siva");

    FREE(test);
    if(test != NULL) //here Im getting issues, test remains pointing address
        printf("\n Failed to free");
    else
        printf("\n Free Success");
    return 0;
}
void *allocate(int count,int  size)
{
    void *ptr;
    ptr = calloc(count,size); // here allocated successfully
    return ptr;

}
void FREE(TEST *ptr)
{
    free(ptr);
    ptr = NULL ; // Deallocated Successfully
}

In this code, i just called one allocation function to allocate memory dynamically, after that i called FREE function to free that memory, both functions working properly only. but inside main function after called the free function, why still test pointer pointing to the memory?


Solution

  • It's because the variable ptr inside the FREE function is a local variable, changing it will only change the local variable, nothing outside of the function will be modified.

    What you need to do is to pass the variable by reference, which is not supported by C. C only have passing by value. But reference argument-passing can be emulated using pointers. So you need to pass a pointer to the pointer:

    void FREE(TEST **ptr);
    

    Call this using the address-of operator &:

    FREE(&test);
    

    and inside the function use the dereference operator * to access the original pointer variable.