Search code examples
cvisual-c++

An unexpected behavior of strcpy_s in Visual Studio


Platform: Win11, VisualStudio 2022 Code:

#include <stdio.h>
#include <string.h>

int main()
{
    char ori[5] = { 'a', 'b', '\0', 'c', 'd' };
    //char *safe = malloc(10 * sizeof(char));
    //char *unsafe = malloc(10 * sizeof(char));

    char safe[10];
    char unsafe[10];
    memset(safe, 0, 10 * sizeof(char));
    memset(unsafe, 0, 10 * sizeof(char));
    strcpy(unsafe, ori);
    strcpy_s(safe, 10, ori);
    printf("SAFE: %c\n", safe[3]);
    printf("UnSafe: %c\n", unsafe[3]);

    return 0;
}

I have two arrays, safe and unsafe. After memset, both of them are initialized as {0,0,0,0,0,0,0,0,0,0} (showing characters as integers).

After strcpy and strcpy_s, I expect to get {'a','b','\0','\0','\0','\0','\0','\0','\0','\0'} in both the safe and unsafe arrays. However, in safe, I obtained {97,98,0,-2,-2,-2,-2,-2,-2,-2} (showing characters as integers).

What does strcpy_s do, and where does the -2 come from?


Solution

  • The official Microsoft documentation for the function strcpy_s states the following:

    The debug library versions of these functions first fill the buffer with 0xFE. To disable this behavior, use _CrtSetDebugFillThreshold.

    If you convert 0xFE to a signed char, you get the value -2.