以下代码有什么问题吗? [英] Is there any problem in the below code?

查看:72
本文介绍了以下代码有什么问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 if malloc fails for buf2 (in such a case buf1 memory is not released).


乍一看,存在潜在的内存泄漏。当 buf2 分配失败时,您不关心前一个( buf1 )并立即从函数返回而不释放 BUF1 。你应该照顾 buf1



例如:

At first glance, there is a potential memory leak. When buf2 allocation fails you don't care about previous one (buf1) and you immediately return from function without freeing buf1. You should take care of buf1.

Eg.:
if (!buf2) {
    free(buf1);

    return -1;
}


这篇关于以下代码有什么问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆