user302520
user302520

Reputation:

Stack Overflow and Segmentation Fault

Does Stack overflow gives segmentation fault in this case, when this infinite recursion runs. I was expecting an error message like "Stack Overflow"!

#include <stdio.h>
int main(){
static int a=1;
printf("%d\n",a);
a++;
main();
return 0;
}

Upvotes: 2

Views: 304

Answers (4)

Janick Bernet
Janick Bernet

Reputation: 21194

As others before posted, it depends on the environment (os, hardware, compiler, etc.). Depending on this, the error message might not reflect the actual cause (as often when doing invalid memory access). That said, running it in something like valgrind should always give you reliable information on the cause of such access.

Upvotes: 0

Jack Edmonds
Jack Edmonds

Reputation: 33171

It will cause a segmentation fault because the stack will overflow.

What happens is that each call to main pushes some more data onto the stack so that your program knows where to jump once it returns from main(). Eventually, you will run out of stack space (a stack overflow). At this point, your next call to main will try to push data to the stack. Since there is no more stack space available, it will accidentally write to an invalid memory location thus triggering the segmentation fault. This is similar to when you write past the end of an array.

Upvotes: 4

hmakholm left over Monica
hmakholm left over Monica

Reputation: 23332

A stack overflow is a cause; the effect of the stack overflow is (in many cases) a segmentation fault. It depends on the OS, architecture and runtime environment whether the code the creates the error message will be able to deduce from the effect that the cause was a stack overflow. But most don't bother to try.

Upvotes: 2

GrandMarquis
GrandMarquis

Reputation: 1913

You're only doing a int overflow.

After reaching his maximum value it go on his minus value.

This recursion will smash you call stack!

void lol()
{
lol();
}

Here it is for buffer overflow: https://www.owasp.org/index.php/Buffer_Overflow

It's not a programming fault but some security issue.

Like you don't verify the password input len, and the guy send you 4000000 chars that will overflow your char* if len declared like char[6].

Upvotes: -2

Related Questions