I have below piece of code
#include <stdio.h>
#include <string.h>
void fn(char *status, size_t maxLen)
{
strcat(status, "1234567890");
}
int main()
{
char status[5] = { 0 };
size_t statusMaxLen = sizeof(status) / sizeof(status[0]);
printf("%s%zu", "size of a status string ", statusMaxLen);
fn(status, statusMaxLen);
return 0;
}
I am getting
run-time check failure #2 - Stack around the variable was corrupted
erro when using strcat. If I replace strcat with strcat_s() like this
strcat_s(status, maxLen, "1234567890");
getting
Debug assertion failed. Buffer is too small
So only type of error is different but still my program crashes. The solution to avoid crash is to check the size before concatenating. In this case why I need strcat_s. strcat also will work fine when size check done. So what will be the real use of strcat_s here.
Whether I use strcat
or strcat_s
, I need to check the size before copying / concatenating. If I do size check, then why should I prefer strcat_s
over strcat
?
if((strlen("1234567890") + strlen(status)) < maxLen){
strcat(status, "1234567890");}`