和前面的memcpy类似, strcpy/strncpy/strcat/strncat都存在内存重叠问题, 为了简便示意起见, 我用strcpy做例子来说明。 值得注意, 有时候, 在你的环境下, strcpy没有出现如下的问题, 不表明他真的没有问题。 看程序:
#include <stdio.h>
#include <string.h>
int main()
{
char str[100] = "abcdefghijklmn";
strncpy(str + 2, str, 5);
printf("%s\n", str);
return 0;
}
结果为:
[root@xxx ~/valgrind-3.8.1/bin]# g++ -g test.cpp
[root@xxx ~/valgrind-3.8.1/bin]# ./a.out
cdefgfghijklmn
[root@xxx ~/valgrind-3.8.1/bin]#
虽然暂时没有异常, 但这也仅仅是运气。 用 valgrind搞起:
[root@xxx ~/valgrind-3.8.1/bin]# g++ -g test.cpp
[root@xxx ~/valgrind-3.8.1/bin]#
[root@xxx ~/valgrind-3.8.1/bin]# ./valgrind --tool=memcheck --leak-check=yes --show-reachable=yes ./a.out
==318== Memcheck, a memory error detector
==318== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==318== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==318== Command: ./a.out
==318==
==318== Source and destination overlap in strncpy(0x7ff000475, 0x7ff000477, 5)
==318== at 0x4C290FF: strncpy (mc_replace_strmem.c:472)
==318== by 0x400640: main (test.cpp:7)
==318==
cdefgfghijklmn
==318==
==318== HEAP SUMMARY:
==318== in use at exit: 0 bytes in 0 blocks
==318== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==318==
==318== All heap blocks were freed -- no leaks are possible
==318==
==318== For counts of detected and suppressed errors, rerun with: -v
==318== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6)
[root@xxx ~/valgrind-3.8.1/bin]#
可见, valgrind是提示了错误的。