strncpy_s函数的异常行为

时间:2013-07-24 13:12:42

标签: c++ windows visual-studio-2010

使用Win32 API在VC ++中开发程序;用于Windows 7 32位操作系统的程序。 我使用string.h中提到的strncpy_s函数进行安全复制,但它在某些机器上崩溃了。

#if __STDC_WANT_SECURE_LIB__
_Check_return_wat_ _CRTIMP_ALTERNATIVE errno_t __cdecl strncpy_s(_Out_z_cap_(_SizeInBytes) char * _Dst, _In_ rsize_t _SizeInBytes, _In_z_ const char * _Src, _In_ rsize_t _MaxCount);
#endif

这是stacktrace

>   msvcr100.dll!malloc(unsigned int size)  Line 89 + 0x3b bytes    C
    mfc100u.dll!operator new(unsigned int nSize)  Line 323 + 0x5 bytes  C++
    MyTest.exe!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::_Copy(unsigned int _Newsize, unsigned int _Oldlen)  Line 1933 + 0x16 bytes C++
    MyTest.exe!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign(const char * _Ptr, unsigned int _Count)  Line 920 + 0x26 bytes  C++
    MyTest.exe!std::basic_stringbuf<char,std::char_traits<char>,std::allocator<char> >::str()  Line 97 + 0x2a bytes C++
    MyTest.exe!std::basic_ostringstream<char,std::char_traits<char>,std::allocator<char> >::str()  Line 593 + 0x12 bytes    C++
    MyTest.exe!Trace<TraceToFile>::~Trace<TraceToFile>()  Line 174 + 0xa bytes  C++
    MyTest.exe!CCommonUtilities::sendDataToClient(std::basic_string<char,std::char_traits<char>,std::allocator<char> > strJson, int nCommandID, std::basic_string<char,std::char_traits<char>,std::allocator<char> > strFuncName, int nLineNumber, int nClientKey)  Line 320    C++
    MyTest.exe!CConnectionManager::AddConnectionThread(void * p_Param)  Line 270 + 0x74 bytes   C++

基于此,有人会指出这是strncpy_s或编程错误的问题吗?

如果我尝试调试代码,我永远不会遇到问题。它总是在我们执行这个二进制文件时出现

非常感谢提前。

2 个答案:

答案 0 :(得分:2)

崩溃不在strncpy_s中 - 它不会出现在堆栈跟踪中。

崩溃是在腐败的记忆中;在您的Trace<>析构函数中,您正在创建一个std::basic_string<>对象,该对象尝试分配内存并发现堆已损坏。

查看~Trace<>CCommonUtilities::sendDataToClient()中的代码,作为查找损坏的起点。

为什么你认为它是strncpy_n()

答案 1 :(得分:0)

strncpy_s的“安全性”并非来自函数的实现,而是来自提供有效输入的调用者,以及检查您没有超出限制的函数。

换句话说,如果你骗过strncpy_s目的地的大小(第二个参数),或者你传递一个无效的地址作为源或目的地,那么它会以某种方式出错。