I am trying to concatenate two strings and then make a system call in a UNIX environmental. The program does what I want but terminates with the error *** stack smashing detected ***
Why is this happening?
Here is my code:
main(int argc, const char* argv[])
{
//Check if there is an arg otehr than file name
if(argc > 1)
{
int i;
//argv[0] is prog name start at 1.
for(i=1; i<argc; i++)
{
char st1[] = "wc -l ";
strcat(st1, argv[i]);
printf("%s",system(st1));
}
}
else
{
printf("\nExiting. No input files given.\n");
}
return 0;
}
str1is not large enough to contain the resulting string as it only has enough elements to containwc -l \0(it is achar[7]array). The call tostrcat()writes beyond the bounds of the array, overwriting memory it should not.Dynamically allocate enough space, calculated based on the length of the incoming argument to ensure enough memory is available: