【问题标题】:What do these valgrind/GNU debugger error messages mean?这些 valgrind/GNU 调试器错误消息是什么意思?
【发布时间】:2014-11-14 00:02:21
【问题描述】:

我的程序正确终止,并且根据 Valgrind 的说法,没有内存泄漏。

但是当对象方法第一次运行时会出现以下消息。

Use of uninitialised value of size 8

获取有关上述产量的更多详细信息

==18787== Use of uninitialised value of size 8
==18787==    at 0x4017F3: Grid::init(int) (grid.cc:90)
==18787==    by 0x401D2A: main (main.cc:43)
==18787==  Uninitialised value was created by a stack allocation
==18787==    at 0x401BE4: main (main.cc:11)

我还看到以下消息:

Conditional jump or move depends on uninitialised value(s)
Invalid free() / delete / delete[] / realloc()
Address 0x7ff000b08 is on thread 1's stack

这里是 Grid::init 的代码

void Grid::init(int n){
    if (!(&(this->theGrid))) { this->clearGrid(); } //If non-empty, destroys grid

    this->theGrid = new Cell*[n]; //Create new grid of size n x n
    this->td = new TextDisplay(n); //new Text Display 
    for (int i = 0; i < n; i++){
        this->theGrid[i] = new Cell[n];
        for(int j = 0; j < n; j++){ //Cell initializations
            (this->theGrid[i][j]).setDisplay(this->td); //set display
            (this->theGrid[i][j]).setCoords(i, j); //set co-ordinates
            (this->theGrid[i][j]).setState(0); //default state
        }
    }
}

【问题讨论】:

  • 那么,Grid::init 的代码是什么,第 90 行是哪一行?
  • ……第 90 行是哪一行?
  • 实际上,任何时候(this->theGrid)第一次被调用,我都会得到相同的未初始化值,大小为 8 错误。
  • if (!(&amp;(this-&gt;theGrid))) 是怎么回事?您似乎正在检查成员变量的地址 - 这可能永远不会是非 NULL (即使 this 是 NULL - 在这种情况下,由于在 NULL 上调用方法,您已经处于危险境地 - @987654328 @ 将会有一些偏移)。
  • @Jay 这应该会揭示您的问题 - 请参阅我的更新答案。

标签: c++ debugging


【解决方案1】:

我猜你的代码看起来像:

条件跳转或移动取决于未初始化的值:

bool value /* nothing */;
if (value) {
}

无效的免费:

char* buf = new char[10000];
buf = &x;
delete [] buf;

既然您发布了代码,我假设第 90 行是这一行:

if (!(&(this->theGrid))) { this->clearGrid(); } //If non-empty, destroys grid

问题是您没有在构造函数中将theGrid 初始化为nullptr,然后您最终可能会得到delete[]-ing 非new[]-ed 数组。此外,如果您这样做,该代码会读起来更清晰:

if (!theGrid) {
    clearGrid();
}

你不需要到处都有this-&gt;。而且我不明白你为什么要使用theGrid的地址。

【讨论】:

  • 其实构造函数有“this->theGrid = NULL;”。改用 nullptr 有什么不同吗?另外 if(!theGrid) 是什么意思?这是否意味着如果 theGrid 不为空?还是说如果 theGrid 为空?
  • 不,它没有,你真的不需要this-&gt; 无处不在。 !theGrid 检查 theGrid 是否为非空。但是您真的想特别检查theGrid 是否为非空,而不是theGrid地址 为非零。这些是不等价的。
猜你喜欢
  • 2011-09-07
  • 1970-01-01
  • 2012-10-20
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多