开发者

Is there a reason why arrays in memory 'go' down while the function stack usually 'goes' up?

开发者 https://www.devze.com 2023-03-31 18:08 出处:网络
Though the actual implementation is platform specific, this idea is the cause for potentially dangerous buffer overflows. For example,

Though the actual implementation is platform specific, this idea is the cause for potentially dangerous buffer overflows. For example,

-------------
|   arr[0]  | \
-------------  \
|   arr[1]  |   -> arr[3] is local to a function
-------------  /
|   arr[2]  | /
-------------
| frame ptr |
-------------
|  ret val 开发者_开发知识库 |
-------------
|  ret addr |
-------------
|    args   |
-------------

My question is, is there a reason why the local array, for lack of a better verb, flows down? Instead, if the array was to flow up, wouldn't it significantly reduce the number of buffer overflow errors that overwrite the return address?

Granted, by using threads, one could overwrite the return address of a function that the current one has called. But lets ignore it for now.


The array on the stack works just like an array on the heap, i.e. its index increases as the memory address increases.

The stack grows downwards (towards lower addresses) instead of upwards, which is the reason for the array going in the opposite direction of the stack. There is some historic reason for that, probably from the time when the code, heap and stack resided in the same memory area, so the heap and the stack grew from each end of the memory.


I can't cite a source for this, but I believe it's so you can step through memory. Consider while *p++ or something along those lines.

Now, you could just as easily say while *p-- but I guess if they had a choice, they'd rather overwrite someone else's data than their own return value :) Talk about a 'greedy algorithm' (har har)


To have a subarray you usually pass just a pointer to it. Any indexing operation would need to know the size of the array, unless you'd like to make all of memory index backwards -- but if you would, you'd just get yourself in the same situation :P.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号