我有一个谜,我没有答案。我用 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!
嗯,看起来不太好。 size 4大概指的是int的大小。正如您最初看到的那样,我使用的是 SIZE 1000,因此结果数组的长度为 1,000,000 个整数。所以,我想,它只是溢出了,我需要一个更大的值类型(至少对于迭代器和结果数组)。我使用了 unsigned long long(unsigned long 的最大值是 18,446,744,073,709,551,615,我只需要 1,000,000 - SIZE*SIZE)。但我仍然收到这些错误消息(他们仍然说读写大小为 4,即使 sizeof(long long) 为 8)。
此外,当我使用较小的 SIZE 时,消息不存在,但无论使用何种类型,它们似乎都恰好在 SIZE 707 时出现。有人有线索吗?我很好奇 :-)。
最佳答案
C 和 C++ 都没有明确限制您可以在堆栈上使用的数组大小,而且通常也没有内置保护。只是不要分配像自动(范围局部)变量这样大的 block 。为此目的,在 C 中使用 malloc
或在 C++ 中使用 new
。
关于c++ - Valgrind - 无效的读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20302543/