There's no possibility to overwrite your buffer if you use it right.
Here. Let's try something. Here's something I wrote quickly. Try to break it:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *szArgs = NULL;
size_t i, len = 0;
for(i=0;i<(size_t)argc;i++)
{
len += strlen(argv[i]) + 1;
}
szArgs = malloc(len);
if(!szArgs)
{
fprintf(stderr, "Unable to allocate buffer of size %d\n", len);
return 1;
}
strcpy(szArgs, argv[0]);
for(i=1;i<(size_t)argc;i++)
{
strcat(szArgs, " ");
strcat(szArgs, argv[i]);
}
printf("szArgs = %s\n", szArgs);
printf("len = %d\n", len);
for(i = 0;i < len;i++)
{
printf("szArgs[%2d] =\t[%3d][%c]\n", i, szArgs[i], szArgs[i]);
}
free(szArgs);
return 0;
}
You can't get this program to write past the boundaries of szArgs, unless I made a simple mistake, which can be corrected.
Of interest, while you are pushing the n versions of the string functions to be safer, I believe Salem mentioned before that the '\0' is left off when using strncpy() if your destination length is less than your source length.
That means you have to add the '\0' yourself in those cases, which just opens the door to more issues.