考虑以下非常简单的 C++ 代码:
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int a[7] = {1, 2, 3, 4, 5, 6, 7};
int b[7];
copy(a, a+7, b);
for (int i=0; i<8; ++i)
cout << b[i] << endl;
}
现在这是我在 gdb 中加载此代码时得到的结果:
(gdb) b 1
Breakpoint 1 at 0x100000a64: file stdcopy.cpp, line 1.
(gdb) r
Starting program: /Users/Babai/pastebin/a.out
Reading symbols for shared libraries ++......................... done
Breakpoint 1, main () at stdcopy.cpp:7
7 int a[7] = {1, 2, 3, 4, 5, 6, 7};
(gdb) n
9 copy(a, a+7, b);
(gdb) s
std::copy<int*, int*> (__first=0x7fff5fbffb8c, __last=0x7fff5fbffba8, __result=0x7fff5fbffb70) at stl_algobase.h:398
398 const bool __in = __is_normal_iterator<_InputIterator>::__value;
(gdb) bt
#0 std::copy<int*, int*> (__first=0x7fff5fbffb8c, __last=0x7fff5fbffba8, __result=0x7fff5fbffb70) at stl_algobase.h:398
#1 0x0000000100000acd in main () at stdcopy.cpp:9
(gdb) up
#1 main () at stdcopy.cpp:10
10 for (int i=0; i<8; ++i)
(gdb) p &a
$1 = (int (*)[7]) 0x7fff5fbffb8c
(gdb) p a + 7
$2 = (int *) 0x7fff5fbffba8
我在这段代码中没有看到任何 valgrind 错误,我想知道为什么。数组 a 有 7 个元素,最多访问 a + 6 没问题,但为什么 valgrind 没有将 a + 7 显示为有效错误?
最佳答案
Valgrind 中的 memcheck 工具不会报告基于堆栈的内存错误(除非您超出堆栈地址空间的顶部)。它报告基于堆 的内存错误。在堆上分配您的数组,Valgrind 应该报告无效读取(不是来自 copy
,而是来自结束后的 for
循环。)
#include <algorithm>
#include <iostream>
#include <cstring>
int main()
{
int* a = new int[7];
int* b = new int[7];
std::memset(a, 0, sizeof(int) * 7);
std::memset(b, 0, sizeof(int) * 7);
std::copy(a, a+7, b);
for (int i=0; i<8; ++i)
std::cout << b[i] << std::endl;
delete[] a;
delete[] b;
}
来自Valgrind manual :
Memcheck is a memory error detector. It can detect the following problems that are common in C and C++ programs.
Accessing memory you shouldn't, e.g. overrunning and underrunning heap blocks, overrunning the top of the stack, and accessing memory after it has been freed. Using undefined values, i.e. values that have not been initialised, or that have been derived from other undefined values.
Incorrect freeing of heap memory, such as double-freeing heap blocks, or mismatched use of malloc/new/new[] versus free/delete/delete[]
Overlapping src and dst pointers in memcpy and related functions.
Memory leaks.
关于c++ - Valgrind 不显示数组复制错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9200302/