如果我执行这个程序,我得到 "Failed to Free"。但是在 FREE 函数中,它只是正确地释放了内存

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
}

在这段代码中,我只调用了一个分配函数来动态分配内存,之后我调用了 FREE 函数来释放内存,这两个函数只能正常工作。但是在调用free函数后的main函数中,为什么还要测试指向内存的指针?

因为FREE函数内部的变量ptr是一个局部变量,改变它只会改变局部变量,函数外的任何东西都不会被改变。

你需要做的是引用传递变量,C不支持,C只能传值 ].但是引用参数传递可以使用指针模拟。所以需要给指针传递一个指针:

void FREE(TEST **ptr);

使用地址运算符调用此函数 &:

FREE(&test);

并在函数内部使用解引用运算符*访问原始指针变量。