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?
If you send
szPath + strlen("C:\\Program Files\\")
as a parameter, then the size of the string issizeof(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.