简体   繁体   English

免费malloc指针局部性问题

[英]free malloc pointer locality issue

I am trying to implement a function set_it_free as shown below, but it would only play with the pointer locally, which does not do what I want, ie free and set to null for a pointer. 我正在尝试实现一个函数set_it_free,如下所示,但它只会在本地使用指针,这不符合我的要求,即free,并为指针设置为null。 Could you help me to modify my set_it_free to make it work? 你能帮我修改一下set_it_free吗?

int set_it_free(void* pointer, unsigned long level, char* message){
logMessage(level, message);
assert  (pointer != NULL);  //Never free a NULL pointer
free    (pointer);          //Free a malloc/calloc/realloc pointer
pointer = NULL;             //Set it to NULL for prevention
return 0;}

I would call it like this in main() 我会在main()中这样称呼它

int* a = (int* )malloc(sizeof(int));
set_it_free(a);
int set_it_free(void** ppointer, unsigned long level, char* message)
{
    logMessage(level, message);
    assert  ( ppointer != NULL);  //Check valid parameter
    assert  (*ppointer != NULL);  //Never free a NULL pointer
    free    (*ppointer);          //Free a malloc/calloc/realloc pointer
    *ppointer = NULL;             //Set it to NULL for prevention
    return 0;
}

And example usage: 示例用法:

sometype* pMyVar = malloc(somesize);
set_it_free(&pMyVar, 5, "freeing myVar");

First of all, in C you should not cast the return values of functions returning void * (like malloc ). 首先,在C中,您不应该转换返回void *的函数的返回值(如malloc )。 It can cause subtle runtime problems if you forget to include the correct header files. 如果您忘记包含正确的头文件,它可能会导致细微的运行时问题。

Secondly, when you pass the pointer pointer to the function, the pointer itself is passed by value, meaning the pointer is copied and any assignment to the local copy inside set_it_free will be only local. 其次,当您将指针pointer传递给函数时,指针本身set_it_free值传递,这意味着指针被复制,并且对set_it_free的本地副本的任何赋值都只是本地的。 This means the assignment to NULL inside the function is only done to the local pointer variable, the pointer a will still point to the now unallocated memory once the function returns. 这意味着函数内部对NULL的赋值仅对本地pointer变量进行,一旦函数返回,指针a仍将指向现在未分配的内存。

For the last problem there are four ways of solving this: The first is to pass the pointer by reference (as in the answer by abelenky), the other is to return the new pointer (similar to what realloc does). 对于最后一个问题,有四种解决方法:第一种是通过引用传递指针(如abelenky的答案),另一种是返回新指针(类似于realloc所做的)。 The third way is to assign to a after the function call, either NULL or make it point to something else. 第三种方式是分配给a函数调用后,无论是NULL或使其指向别的东西。 The fourth way is to simply not use the variable a again. 第四种方法是不再使用变量a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM