3

I feel like I've always used strcpy to copy strings without having any trouble, but I haven't done it for a long time and now I can't get it to work no matter what I do.

I'm sure there's something dumb I'm missing, but I've been frustrated with this for a while so I'm here to see if anybody else can help.

const char* src = "Lalalala";
int strLen = strlen(src);
char* dest = new char[strLen + 1];
ZeroMemory(dest, strLen + 1);
strcpy_s(dest, strLen, src);

This code throws me an exception saying that the lBuffer is too small. Even if I try copying just "one byte" of data, and allocate a buffer of 128 bytes, it throws the same exception.

Also, I've checked that strlen returns the expected value, the allocation and the "ZeroMemory" function call work fine, and it's only when running the strcpy_s() function that the program crashes. I don't know what's going on here, please help!

Thanks

1 Answers1

5

The second parameter of strcpy_s is numberOfElements. This is the buffer size, not string length.

From MSDN:

numberOfElements
     Size of the destination string buffer in char units for narrow and multi-byte functions, and wchar_t units for wide functions.

When you call strcpy_s in your example above, you're passing 8 as the length of the buffer, but strcpy_s wants to copy 9 characters. 8 characters of the string + 1 null terminator. It sees the buffer isn't big enough, and throws.

Try passing strLen + 1 which is the actual size of the buffer. Should work there.

lcs
  • 4,227
  • 17
  • 36
  • That was it, thank you so much! I thought that since I had called ZeroMemory before it already had the null terminator so I only needed to copy the 8 regular characters and leave that as is. I didn't realize that's what the second parameter meant. Thank you again! ;) – danielmlima Nov 12 '15 at 16:43