Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a segmentation fault and a stack overflow?

For example when we call say, a recursive function, the successive calls are stored in the stack. However, due to an error if it goes on infinitely the error is 'Segmentation fault' (as seen on GCC).

Shouldn't it have been 'stack-overflow'? What then is the basic difference between the two?

Btw, an explanation would be more helpful than wikipedia links (gone through that, but no answer to specific query).

like image 861
AruniRC Avatar asked Apr 21 '10 18:04

AruniRC


People also ask

Is segmentation fault and stack overflow the same?

Yes, a stack overflow can cause a segmentation fault and core dump, but not always, it can also cause security breaches, and allow code to run that should not, it depends on how the software is designed and what precautions are taken.

Can stack overflow cause segmentation fault?

Infinite recursionThe function foo, when it is invoked, continues to invoke itself, allocating additional space on the stack each time, until the stack overflows resulting in a segmentation fault.

What is meant by segmentation fault?

A segmentation fault (aka segfault) is a common condition that causes programs to crash; they are often associated with a file named core . Segfaults are caused by a program trying to read or write an illegal memory location.

Is stack smashing a seg fault?

Stack smashing in X86_64 leads to Segmentation fault .


2 Answers

Stack overflow is [a] cause, segmentation fault is the result.


At least on x86 and ARM, the "stack" is a piece of memory reserved for placing local variables and return addresses of function calls. When the stack is exhausted, the memory outside of the reserved area will be accessed. But the app did not ask the kernel for this memory, thus a SegFault will be generated for memory protection.

like image 64
kennytm Avatar answered Sep 20 '22 21:09

kennytm


Modern processors use memory managers to protect processes from each other. The x86 memory manager has many legacy features, one of which is segmentation. Segmentation is meant to keep programs from manipulating memory in certain ways. For instance, one segment might be marked read-only and the code would be put there, while another segment is read/write and that's where your data goes.

During a stack overflow, you exhaust all of the space allocated to one of your segments, and then your program starts writing into segments that the memory manager does not permit, and then you get a segmentation fault.

like image 41
ajs410 Avatar answered Sep 17 '22 21:09

ajs410