"DanielJohnson" <di********@gmail.comwrote:
[ That's a misleading subject, BTW. It's not really about a segfault. ]
int main()
{
printf("\n Hello World");
main;
return 0;
}
This program terminate just after one loop while the second program
goes on infinitely untill segmentation fault (core dumped) on gcc. The
only difference is that in first I only call "main" and in second call
"main()".
Nope. The difference is that in the first you don't call main at all.
You evaluate the expression main. Any function name, including that of
main, decays to a function pointer in nearly all circumstances. In this
case, the only thing you do with that function pointer is to find its
value in the context of an expression statement - and since you do
nothing with it, it's forgotten immediately. It's no different, in this
case, from if you had written any_existing_variable_name;, or 42;.
In your other program, you had main(); instead of main;. That's also an
expression statement: it consists of the function pointer main, to which
the function call operator () is applied. So in that case, main() _does_
get called. Infinitely recursively, in your case.
In what all cases does segmentation fault occurs.
That's rather system-dependent and not specified by ISO C (in fact, ISO
C doesn't specify anything called a "segmentation fault" at all); but in
general, it occurs when you do something wrong with memory. This is a
rather large area, so a list of "all cases", even if not system-
dependent, would be hard to post accurately. Overflowing the call stack,
as you did in your second program, can - but is not required to! - do
it.
Richard