During a call to function B() from function A(), B() allocates a 100-char array and fills it several times, including once with a 101-character string and once with a 110 character string. This is an obvious mistake.
Later, function A() tries to access completely unrelated int variable i, and a segmentation fault occurs.
I understand why the buffer overrun occurs, but why do I get a segmentation fault when I access this integer? Why is it that I don't simply get garbage data?
When A()
calls B()
, B's preamble instructions save A's frame pointer—the location on the stack where A keeps local variables, before replacing it with B's own frame pointer. It looks like this:
When B overruns its local variables, it messes up the value which will be reloaded into the frame pointer. This is garbage as a frame pointer value, so all of A's local variables are trashed. Worse, future writes to local variables are messing with memory belonging to someone else.
A buffer overrun may clobber a previously saved version of the frame pointer on the stack. When the function returns, this corrupt version is loaded into the frame pointer register, causing the behavior you describe.
Wikipedia's page contains a figure and definitions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With