我编写了一个使用堆栈 ADT 的程序。
main 创建一个新的堆栈,同时提供 3 个函数供用户使用:
Stack my_stack = sCreate (copy_int, free_int, print_int);
当我调用“peek”函数时:
printf ("Peek: |%d|\n\n", *(int*)sPeek(my_stack));
我有内存泄漏。
peek 函数如下所示:
Element sPeek (Stack stack){
if ((NULL == stack) || (0 >= stack->used_places))
return NULL;
Element returnElement = stack->copy_function(stack->stack_array[stack->used_places-1]);
if (NULL == returnElement){
free (returnElement);
return NULL;
}
return returnElement;
可能是这里调用的copy_function导致的,也就是用户给的copy_int:
Element copy_int (Element element){
int *new_int = (int*) malloc(sizeof(int*));
*new_int = *(int*)element;
if (NULL != new_int)
return new_int;
else
return NULL;
如何从 copy_int 释放指针 (malloc)?
最佳答案
Element e = sPeek(my_stack);
if (e) {
printf ("Peek: |%d|\n\n", *(int*)e);
}
free(e);
看起来有点明显,所以不确定这是否是您的意思。
关于c - 从外部函数中释放指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32132958/