Hi,
I wrote the following C++ constructor, and I get an error - BUFFER too small on strcpy_s
Code:
Trace::Trace(const char *str)
{
if (str)
{
int len = strlen(str);
this->m_name = new char[len+1]; // asking for 'len+1' memory elements of char
strcpy_s(m_name, len, str); // **** I get here an error "BUFFER TOO SMALL" ****
cout << "start of " << m_name << endl;
}
else
{
m_name = new char[1];
m_name[0] = '\0';
}
}
It will work ("The destination string must be large enough to hold the source string, including the terminating null character.") but strcpy_s is non-standard and MS specific. Memcpy will work with PODs in C++.
If you read the description of strcpy_s(), you'll see that the second argument the size of the buffer. By passing len you say:
Dear strcpy_s() function, I want to copy the string from src to dst, but my dst is only len bytes long. Make sure not to overrun it.
strcpy_s() tries to copy and finds out that copying would require to put len+1 characters into the dst buffer. So it says:
Dear electroRF, I would be glad to copy for you. I would need len+1 characters, but you told me that only len is available. So, I better return the "Buffer too small" error.
This would work:
C:
strcpy_s(m_name, len+1, str);
However, using memcpy() would be better because you already know the length.