Re: Why are variables stored on the stack?
- From: santosh <santosh.k83@xxxxxxxxx>
- Date: Sat, 15 Mar 2008 19:52:45 +0530
Bartc wrote:
"CJ" <cj@xxxxxxxxxx> wrote in message
news:slrnftn8uu.3lg.nospam@xxxxxxxxxxxxxxxxx
Thanks for all the replies, this is an interesting discussion.
Here are a couple of points that occur to me:
1) Buffer overflows are a more serious security problem on the stack
than on the heap, because the program counter is stored on the stack
and not the heap, so that a malicious stack overflow can execute
arbitrary code. The heap is used for data exclusively, which is what
I meant by "separate data from executable code".
Even if a buffer on the heap overflows, the worst that can happen is
some (probably insignificant) data corruption. Since malloc()
generally allocates space in powers of 2, often an off-by-one error
or similar won't overwrite anything anyway, but will just land in the
gap between the end of the buffer and the next power of 2.
2) I believe the argument about it being more efficient to use the
stack than the heap is spurious - if I recall, both are O(N) data
structures.
The heap is a fragmented resource and requires a function call to
allocate and deallocate.
The stack, by it's nature, is unfragmented and allocation and
deallocation is very fast, especially when hardware assisted.
To address your other concerns, then yes it might be a good idea to
have a compiler option to put auto-data on the heap, to avoid
accidental or malicious overwrite of critical data. But your
applications might run 10-100 x slower if they do lots of function
calls.
The compiler could have special support, translating auto declarations
into some sequence of compiler magic. A function call needn't be
involved, I think.
But in practice, if there was such an option, the compiler would
simply create a separate, linear data-stack with a software stack
pointer. And performance would be little affected. So your idea is a
good one.
It is an idea which has been implemented by a lot of languages, like for
example Java. But it's not really suitable for C, since C is mainly
used for low level programming where this will either not be possible
or will impact performance unacceptably.
.
- References:
- Why are variables stored on the stack?
- From: CJ
- Re: Why are variables stored on the stack?
- From: CJ
- Re: Why are variables stored on the stack?
- From: Bartc
- Why are variables stored on the stack?
- Prev by Date: Re: scanf()/fscanf() question
- Next by Date: Re: Why are variables stored on the stack?
- Previous by thread: Re: Why are variables stored on the stack?
- Next by thread: Re: Why are variables stored on the stack?
- Index(es):
Relevant Pages
|