jimboweb jimboweb - 2 months ago 10
C Question

can't strcat_s multiple characters to string pointer

I'm trying to concatenate multiple strings to a string pointer to which I've allocated memory. Here's an example:

char *finalNumString = malloc(sizeof(char)*1024);
finalNumString[0] = '\0';
strcat_s(finalNumString, 10, "abcabcabc");
printf("added %d chars to finalNumString\n", 10);
strcat_s(finalNumString, 10, "abcabcabc");
printf("added %d chars to finalNumString\n", 10);
strcat_s(finalNumString, 10, "abcabcabc");
printf("added %d chars to finalNumString\n", 10);


After the first strcat_s command I get the error 'Debug assertion failed: L buffer is too small.' But I have malloc'd the memory! Why does this not work?

Answer

According to msdn page of strcat_s() function, it's definition is:

errno_t strcat_s(
   char *strDestination,
   size_t numberOfElements,
   const char *strSource 
);

here, numberOfElements refers to Size of the destination string buffer. So you need to send in 1024(which is size of the destination string) as your second argument instead of 10 each time you use the strcat_s() function this way:

strcat_s(finalNumString, 1024, "abcabcabc");