==7661== Memcheck, a memory error detector ==7661== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al. ==7661== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info ==7661== Command: ./memleak ==7661== ==7661== ==7661== HEAP SUMMARY: ==7661== in use at exit: 72,716 bytes in 2 blocks ==7661== total heap usage: 4 allocs, 2 frees, 72,752 bytes allocated ==7661== ==7661== LEAK SUMMARY: ==7661== definitely lost: 12 bytes in 1 blocks ==7661== indirectly lost: 0 bytes in 0 blocks ==7661== possibly lost: 0 bytes in 0 blocks ==7661== still reachable: 72,704 bytes in 1 blocks ==7661== suppressed: 0 bytes in 0 blocks ==7661== Rerun with --leak-check=full to see details of leaked memory ==7661== ==7661== For counts of detected and suppressed errors, rerun with: -v ==7661== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
使用 memcheck 检查 overlap
strncpy.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<cstring> #include<iostream>
usingnamespacestd;
intmain(){ char s[60]; memset(s, '*', sizeof(s)); strcpy(s, "abcdefghijklmnopqrstuvwxyz"); strncpy(s + 26, s, 26); for (int i = 0; i < 60; i++) cout << (s[i] ? s[i] : '_'); cout << '\n'; strncpy(s + 26, s, 27); for (int i = 0; i < 60; i++) cout << (s[i] ? s[i] : '_'); cout << '\n'; return0; }
==7561== Source and destination overlap in strncpy(0xfff0003d5, 0xfff0003bb, 27) ==7561== at 0x4C31626: __strncpy_sse2_unaligned (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==7561== by 0x400951: main (strncpy.cpp:13)