-1
int main()
{
  const int SIZE = 4;

  char pin[SIZE] = { 1, 2, 3, 4 };
  char temp[SIZE+1];

  strcpy_s(temp, SIZE+1, pin);

  return 0;
}

This code throws "Buffer is too small" exception. However, it starts working if I make temp 14 or more:

  char temp[14];

  strcpy_s(temp, 14, pin);

^ Works ^

Why does it start working only after 14?

Vegeta
  • 334
  • 2
  • 4
  • 12

1 Answers1

4

This is because strcpy_s() is expecting the source string to be a null terminated C-String.

You are passing it an array of char. But you have not null terminated the array (so it does not act like a C-String). When you expand the destination it works just randomly because it is readong passed the end of pin and just happens to find a byte in memory that is zero before the 14th byte.

Reading passed the end of the end of an array is undefined behavior. So your program is illformed.

Martin York
  • 257,169
  • 86
  • 333
  • 562