Valgrind-无效的读写

Valgrind - invalid read and write

本文关键字:读写 无效 Valgrind-      更新时间:2023-10-16

我有一个谜,我没有答案。我用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的大小。正如你所看到的,一开始我使用的是SIZE1000,所以结果数组的长度是1000000 int。所以,我想,它只是溢出了,我需要一个更大的值类型(至少对于迭代器和结果数组)。我使用了无符号长整型(无符号长型的最大值为18446744073709551615,我只需要1000000-SIZE*SIZE)。但我仍然收到这些错误消息(他们仍然说读写大小是4,尽管sizeof(long-long)是8)。

此外,当我使用较低的SIZE时,这些消息就不存在了,但无论使用的类型如何,它们似乎都正好在SIZE 707处出现。有人知道线索吗?我很好奇:-)。

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