以下代码有什么问题吗? [英] Is there any problem in the below code?
本文介绍了以下代码有什么问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int foo(int in)
{
int *buf1 = (int *)malloc(1000*sizeof(int));
if(!buf1) return -1;
int *buf2 = (int *)malloc(2000*sizeof(int));
if(!buf2) return -1;
int retVal = process(in,buf1,buf2);
free(buf1);
free(buf2);
return retVal;
}
我的尝试:
我无法找到任何错误,请提示是否有任何错误?
What I have tried:
I am not able to find any bug, please suggest if any is there?
推荐答案
代码几乎没问题:你有内存泄漏如果malloc
对于buf2
失败(在这种情况下buf1
内存未释放。)
The code is almost fine: you have a memory leak ifmalloc
fails forbuf2
(in such a casebuf1
memory is not released).
乍一看,存在潜在的内存泄漏。当buf2
分配失败时,您不关心前一个(buf1
)并立即从函数返回而不释放BUF1
。你应该照顾buf1
。
例如:
At first glance, there is a potential memory leak. Whenbuf2
allocation fails you don't care about previous one (buf1
) and you immediately return from function without freeingbuf1
. You should take care ofbuf1
.
Eg.:
if (!buf2) {
free(buf1);
return -1;
}
这篇关于以下代码有什么问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文