-2

Developing a program in VC++ using Win32 API;s for Windows 7 32-bit OS. I used strncpy_s function mentioned in string.h for secure copying, but it crashes in some machines.

#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

Here is the 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++

Based on this, can someone point if this is issue with strncpy_s or programming error ?

I never get issue if I try to debug the code. It always come when we execute this binary.

Many Thanks in advance.

4

2 回答 2

2

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

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

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

为什么你认为它是strncpy_n()

于 2013-07-24T13:41:38.400 回答
0

的“安全性”strncpy_s与其说来自函数的实现,不如说来自提供有效输入的调用者,以及检查你没有超出限制的函数。

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

于 2013-07-24T13:21:30.017 回答