Why does this cause a segmentation error and that does not?

Viewed 40

Why does this cause a segmentation error,

int main(char *argv[]) 
{
    printf("%s\n", argv[0]);
    return 0;
}

and why doesn't this

int main(int argc, char *argv[]) {
    int i = 0;
    printf("\ncmdline args count=%d", argc);

    /* First argument is executable name only */
    printf("\nexe name=%s", argv[0]);

    for (i = 1; i < argc; i++) {
        printf("\narg%d=%s", i, argv[i]);
    }

    printf("\n");
    return 0;
}

I don't get the difference. However I am a total noob in terms of C-programming.

2 Answers

The first program has an invalid prototype for main: int main(char *argv[]).

This has undefined behavior, which in your case is a crash.

The second program is correct and executes as expected.

The first one, presuming there is no valid implementation-defined behavior for it, has an unsupported definition of main().

From the C11 Standard:

5.1.2.2.1 Program startup

The function called at program startup is named main . The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv , though any names may be used, as they are local to the function in which they are declared):

int main(int argc, char *argv[]) { /* ... */ }

or equivalent; or in some other implementation-defined manner.

Related