Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would buffer overruns cause segmentation faults when accessing an integer?

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?

like image 733
skiphoppy Avatar asked Nov 30 '22 06:11

skiphoppy


2 Answers

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:

Stack Frame

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.

like image 35
wallyk Avatar answered Dec 01 '22 19:12

wallyk


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.

like image 76
Pascal Cuoq Avatar answered Dec 01 '22 19:12

Pascal Cuoq