0

I have the following C++ code:

std::string test = "ABC";
char buffer[30];

for (int i = 0; i < 30; i++)
    buffer[i] = 0;

strcpy_s(buffer, 30, test.c_str());

After running it, I expect buffer to be: [0x41, 0x42, 0x43, 0x00, 0x00, 0x00, 0x00, ... 0x00] up to its end (29th position).

Running in VS2012, I´m getting the following result: [0x41, 0x42, 0x43, 0x00, 0xFE, 0xFE, 0xFE, ... 0xFE]

Why is strcpy_s copying more than my string length (3 chars + \0) ? Where is that 0xFE coming from ?

Mendes
  • 17,489
  • 35
  • 150
  • 263
  • **...it may clobber the rest of the destination array with unspecified values...** Syntax 2) http://en.cppreference.com/w/c/string/byte/strcpy – Killzone Kid Mar 13 '18 at 16:13

1 Answers1

2

This is allowed by strcpy_s:

strcpy_s is allowed to clobber the destination array from the last character written up to destsz in order to improve efficiency: it may copy in multibyte blocks and then check for null bytes.

YSC
  • 38,212
  • 9
  • 96
  • 149