Valgrind - 读写无效

时间:2013-11-30 16:19:50

标签: c++ c valgrind

我有一个谜,我没有答案。我用C ++编写了一个简单的程序(我应该说我不是一个专业的C ++开发人员)。这是:

#include <iostream>

int main(){
  const int SIZE = 1000;
  int pool1 [SIZE];
  int pool2 [SIZE];
  int result [SIZE*SIZE];

  //Prepare data
  for(int i = 0; i < SIZE; i++){
    pool1[i] = i + 1;
    pool2[i] = SIZE - i;
  }

  //Run test
  for(int i = 0; i < SIZE; i++){
    for(int j = 0; j < SIZE; j++){
      result[i*SIZE + j] = pool1[i]*pool2[j];
    }
  }

  return 0; 
}

该程序似乎有用(我将它用作不同语言的一种基准)但后来我用valgrind运行它并开始抱怨:

==25912== Invalid read of size 4
==25912==    at 0x804864B: main (in /home/renra/Dev/Benchmarks/array_iteration/array_iteration_cpp)
==25912==  Address 0xbee79da0 is on thread 1's stack

==25912== Invalid write of size 4
==25912==    at 0x8048632: main (in /home/renra/Dev/Benchmarks/array_iteration/array_iteration_cpp)
==25912==  Address 0xbeaa9498 is on thread 1's stack

==25912== More than 10000000 total errors detected.  I'm not reporting any more.
==25912== Final error counts will be inaccurate.  Go fix your program!
嗯,看起来不太好。大小4可能是指int的大小。正如您最初看到的那样,我使用的是SIZE 1000,因此结果数组的长度为1,000,000英寸。所以,我想,它只是溢出而且我需要一个更大的值类型(至少对于迭代器和结果数组)。我使用无符号长多(无符号长的最大值是18,446,744,073,709,551,615,我需要的是1,000,000 - SIZE * SIZE)。但我仍然收到这些错误消息(他们仍然说即使sizeof(long long)为8,读写大小也是4)。

当我使用较低的SIZE时,消息也不存在,但无论使用何种类型,它们似乎都在SIZE 707中完全启动。有人有线索吗?我很好奇: - )。

1 个答案:

答案 0 :(得分:3)

C和C ++都没有明确限制你可以在堆栈上使用的数组大小,也通常没有内置保护。只是不要分配像自动(范围本地)变量这样的大块。在C中使用malloc或在C ++中使用new用于此目的。