c++ 中的动态二维数组和内存泄漏

发布于 2024-08-30 04:24:24 字数 524 浏览 6 评论 0原文

我写了这段代码。它运行正常,但是当我在 Valgrind 下检查它时,它发现了 2 个问题。由于我无法解释 valgrind 的消息,如果有人进一步解释我并告诉我问题出在哪里,我将不胜感激!

这是代码:

#include <iostream>

#define width  70000 
#define height 10000

using namespace std;

int main(void)
{
    int** pint; 

    pint = new int*[height];
    for(int i = 0; i < height; i++)
        pint[i] = new int[width];

    for(int i = 0; i < height; i++){
        delete[] pint[i];
        pint[i] = NULL;
    }

    delete[] pint;
    pint = NULL;


    return 1;
}

I wrote this code. It runs OK, but when I check it under Valgrind it catches 2 problems. Since I can not interpret valgrind's messages i will appreciate if anyone explain me more and tell me where is the problem!!!

Here is the code:

#include <iostream>

#define width  70000 
#define height 10000

using namespace std;

int main(void)
{
    int** pint; 

    pint = new int*[height];
    for(int i = 0; i < height; i++)
        pint[i] = new int[width];

    for(int i = 0; i < height; i++){
        delete[] pint[i];
        pint[i] = NULL;
    }

    delete[] pint;
    pint = NULL;


    return 1;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

当梦初醒 2024-09-06 04:24:24

好吧,我在 3.4 版本中收到了一些 Valgrind 警告,但只有第一个是重要的。

new/new[] 失败,应该抛出异常,但 Valgrind 不能抛出异常,因此正在中止。抱歉。

new 当内存不足时会抛出异常(除非你使用 new 的 nothrow 版本)。不幸的是,Valgrind 无法处理这个问题并在代码完成之前放弃。因为 valgrind 中止,所以释放内存的代码永远不会执行,这会显示为内存泄漏。

也就是说,您没有处理 new 抛出的情况,因此如果内存不足,您的程序将由于未处理的异常而死亡。您需要用 try/ except 块包装您的代码。

Okay, there are a couple of Valgrind warnings I get with 3.4 but only the first is important.

new/new[] failed and should throw an exception, but Valgrind cannot throw exceptions and so is aborting instead. Sorry.

new throws an exception when it is out of memory (unless you use the nothrow version of new). Unfortunately, Valgrind cannot handle that and gives up before your code completes. Because valgrind aborts, you code to free up memory is never executed which shows up as memory leaks.

That said, you are not handling the case where new throws so your program will die due to an unhandled exception if you run out of memory. You need to wrap your code with a try/except block.

谁人与我共长歌 2024-09-06 04:24:24

在我看来,它似乎在抱怨某些 new[] 失败了。如果减小 height 和/或 width 的大小,那么它就可以正常工作。您可能尝试分配过多的内存。

编辑:这是在我的 32 位机器上。如果我在 64 位机器上运行它,那就没问题了。因此,您可能会达到 32 位计算机上的内存限制。

It looks to me like it's complaining that some of the new[]s are failing. If you reduce the size of height and/or width, then it works fine. You're likely trying to allocate too much memory.

EDIT: That's on my 32-bit box. If I run it on my 64-bit box, it's fine. So, you're likely hitting a memory limit on a 32-bit machine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文