我写了一个使用堆栈ADT的程序.
main创建一个新堆栈,同时提供3个函数供用户使用:
Stack my_stack = sCreate (copy_int, free_int, print_int);
Run Code Online (Sandbox Code Playgroud)
当我打电话给'偷看'功能时:
printf ("Peek: |%d|\n\n", *(int*)sPeek(my_stack));
Run Code Online (Sandbox Code Playgroud)
我有内存泄漏.
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;
Run Code Online (Sandbox Code Playgroud)
它可能是由那里调用的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;
Run Code Online (Sandbox Code Playgroud)
如何从copy_int释放指针(malloc)?
在最后一个代码片段中,您使用*new_intbefore 检查 的返回值malloc。new_int如果是的话,这将导致分段错误NULL。此外,if/else正如所写的那样,它完全没有价值。这四行可以被替换,return new_int;在任何情况下行为都绝对不会改变。最后,不要转换 malloc 的返回值。
解决所有这些问题后,最后的代码片段如下所示
Element copy_int (Element element)
{
int *new_int = malloc(sizeof(int));
if ( new_int )
*new_int = *(int*)element;
return new_int;
}
Run Code Online (Sandbox Code Playgroud)
在sPeek函数中,你有一个类似的毫无价值的if语句。如果returnElement是的话NULL,那就没什么可做的了free。所以sPeek函数应该是
Element sPeek (Stack stack)
{
if ( stack && stack->used_places > 0 )
return stack->copy_function(stack->stack_array[stack->used_places-1]);
else
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
最后,对于您的问题,除非您保留该指针的副本以及完成后的副本,否则返回的内存copy_int 将被泄漏。free另外,如果您将 NULL 指针传递给 ,则会出现另一个分段错误printf。因此该printf行需要替换为此代码(假设Element确实如此void *)
int *value = sPeek(my_stack);
if (value)
printf ("Peek: |%d|\n\n", *value);
free(value);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |