Nick
Nick

Reputation: 9373

Simple program results in "Stack Smashing"

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;
}

Upvotes: 0

Views: 136

Answers (2)

JasonD
JasonD

Reputation: 16582

char st1[] = "wc -l ";
strcat(st1, argv[i]);

st1 will be allocated on the stack, just large enough for the string constant used to initialise it. You then append another string, potentially (almost certainly) corrupting the stack.

Upvotes: 0

hmjd
hmjd

Reputation: 121961

str1 is not large enough to contain the resulting string as it only has enough elements to contain wc -l \0 (it is a char[7] array). The call to strcat() 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:

char* s = malloc(7 + strlen(argv[i])); /* 7 is 6 for "wc -l " and null term. */
if (s)
{
    sprintf(s, "wc -l %s", argv[i]);

    free(s);
}

Upvotes: 2

Related Questions