加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 全局分配的内存会发生什么变化?

发布时间:2020-12-16 09:52:16 所属栏目:百科 来源:网络整理
导读:我有一个这样的程序: int *number0 = new int;int main(){ int *number1 = new int;} 我想,两个内存分配都会引入内存泄漏,尽管只有valgrind 抱怨主要功能内的number1.这是为什么? 解决方法 运行这个 int *x = new int;int main(){ return 0;} 使用valgrind
我有一个这样的程序:

int *number0 = new int;

int main()
{
    int *number1 = new int;
}

我想,两个内存分配都会引入内存泄漏,尽管只有valgrind
抱怨主要功能内的number1.这是为什么?

解决方法

运行这个

int *x = new int;

int main()
{   
    return 0;
}

使用valgrind(3.8.1)和(-v -track-originins = yes –leak-check = full –show-reachable = yes)使用valgrind(3.8.1)进行代码(即没有主要的泄漏,用g 4.8.1编译)我明白了:

==34301== 
==34301== HEAP SUMMARY:
==34301==     in use at exit: 4 bytes in 1 blocks
==34301==   total heap usage: 1 allocs,0 frees,4 bytes allocated
==34301== 
==34301== Searching for pointers to 1 not-freed blocks
==34301== Checked 189,064 bytes
==34301== 
==34301== 4 bytes in 1 blocks are still reachable in loss record 1 of 1
==34301==    at 0x4C2A879: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==34301== 
==34301== LEAK SUMMARY:
==34301==    definitely lost: 0 bytes in 0 blocks
==34301==    indirectly lost: 0 bytes in 0 blocks
==34301==      possibly lost: 0 bytes in 0 blocks
==34301==    still reachable: 4 bytes in 1 blocks
==34301==         suppressed: 0 bytes in 0 blocks

这意味着您还应该注意退出类别中的使用情况.

看起来valgrind似乎没有错过它,只是把它放在另一个类别中,可能是因为只有当你无法通过任何方式追踪该地址并释放它时它们才会假设丢失的东西,但这个变量永远不会丢失.

但是这样:

int *x = new int;

int main()
{

    x = new int;    
    return 0;
}

被检测为泄漏,因为您真的忘记了已分配的内存.

编辑:如Mem-check manual中所述:

“Still reachable”. This covers cases 1 and 2 (for the BBB blocks)
above. A start-pointer or chain of start-pointers to the block is
found. Since the block is still pointed at,the programmer could,at
least in principle,have freed it before program exit. “Still
reachable” blocks are very common and arguably not a problem. So,by
default,Memcheck won’t report such blocks individually.

因此,如前所述他们确实发现了它,他们只是认为它不那么令人兴奋

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读