Error that the stack was damaged while using strcat_s

147 views Asked by At

I was studying strcat_s and I wrote the following code to practice it.

int main(void)
{
    char szPath[128] = { "C:\\Program Files\\" };

    strcat_s(szPath + strlen("C:\\Program Files\\"), sizeof(szPath), "CHS\\");
    strcat_s(szPath + strlen("C:\\Program Files\\CHS\\"), sizeof(szPath), "C programming");
    puts(szPath);
    return 0;
}

The output worked properly like C:\Program Files\CHS\C programming

but a debug error window popped up,

Stack around the variable 'szPath' was corrupted. What is the cause?

2

There are 2 answers

0
Michael On BEST ANSWER

If you send szPath + strlen("C:\\Program Files\\") as a parameter, then the size of the string is sizeof(szPath) - strlen("C:\\Program Files\\").

Same for the second line - size is sizeof(szPath) - strlen("C:\\Program Files\\CHS\\").

The string size is 128, but you send a pointer to the middle, where the number of available characters is smaller.

0
Alan Birtles On

Looks like the debug version of strcat_s in visual studio deliberately overwrites the full length of the buffer: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strcat-s-wcscat-s-mbscat-s?view=vs-2019

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

This means that if you give a size value that is too large the debug runtime should detect this by corrupting the stack.

In your case you aren't passing a pointer to the beginning of the buffer so your size is strlen bytes more than the available space. The simplest solution to to just pass the pointer unmodified to strcat_s, it does the strlen internally to find the current end of the string:

int main(void)
{
    char szPath[128] = { "C:\\Program Files\\" };

    strcat_s(szPath, sizeof(szPath), "CHS\\");
    strcat_s(szPath, sizeof(szPath), "C programming");
    puts(szPath);
    return 0;
}