On Apr 3, 6:35 am, Goran <goran.pu...@gmail.com> wrote:
> On Apr 1, 7:32 pm, "crea" <n...@invalid.com> wrote:
[...]
> > So my question is, that why cant I destroy this automatic
> > object? How/why does the compiler prevent that?
> Compiler does not prevent it. For example:
> void f()
> {
> int i; // automatic
> int* p = &i;
> delete p; // boom
> }
> This code is 100% legal, and compiler will compile it without any
> complaint. But at runtime, boom!
The code is not "legal" (for the usual definition of legal). It
has undefined behavior. One possible behavior is that the
compiler refuse to compile it, or issues an error message.
Another is that something strange happens at runtime.
[...]
> Automatic objects are normally on the stack (I don't know whether
> language specifies what "stack" is, so what I am saying is most likely
> implementation-specific, but extremely common), and yes, these are
> "specific" memory parts.
The language doesn't speak directly of a stack, but the
lifetimes of such objects does obey stack semantics, so putting
them on a stack is an obvious implementation solution. (I have
seen a C implementation where the compiler used the equivalent
of malloc to get each stack frame. A long long time ago, and it
has serious performance problems. But the implementation is
clearly legal.)
> Most notably, pointers given to you by operator new do not
> point into stack. I don't know what you mean by
> "reallocation", though, but I am guessing that this is 100%
> orthogonal to your initial question.
It might be worth pointing out that when local variables do go
out of scope, the memory they occupy will be reused by other
variables.
--
James Kanze
|