Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
}

Ques Description:
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} (describing 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} (describing characters as integers).
What does strcpy_s do, and where does the ‘-2’ come from?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading