Valgrind-无效的读写
Valgrind - invalid read and write
我有一个谜,我没有答案。我用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
。
相关文章:
- 用C++快速读写文件
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 在一个读写器队列中,我可以用volatile替换原子吗
- C++套接字对不读/写父/子
- 如何调试读写器锁的死锁?
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- Linux 挂载使用重新挂载以允许读写
- C++中读/写二进制文件
- 如何读/写或遍历 std::array 中的特定元素范围?
- 内存排序或读取-修改-写入操作,仅(读/写)内存顺序
- USB-HID 读/写(重叠)等待单个对象不返回C++
- 为什么使用_access时只读测试对读写文件有效
- Boost::Asio串行读/写打开:参数不正确
- 读/写 OpenMP 中的共享向量会减慢程序速度
- 谷歌测试读写同一文件失败
- Android USB 附件模式无法使用 libusb 与主机 PC 一起读/写
- 特定时间间隔 C++ 上的读写日志
- Valgrind 显示无效的读/写错误,但我不使用 new 或 calloc,只使用向量和固定数组
- Valgrind-无效的读写