Ignoring programming style and design, is it \"safe\" to call delete on a variable allocated on the stack?
For example:
int nAmount;
delete &am
Yes, it is undefined behavior: passing to delete
anything that did not come from new
is UB:
C++ standard, section 3.7.3.2.3: The value of the first argument supplied to one of thea deallocation functions provided in the standard library may be a
null
pointer value; if so, and if the deallocation function is one supplied in the standard library, the call to the deallocation function has no effect. Otherwise, the value supplied tooperator delete(void*)
in the standard library shall be one of the values returned by a previous invocation of eitheroperator new(std::size_t)
oroperator new(std::size_t, const std::nothrow_t&)
in the standard library.
The consequences of undefined behavior are, well, undefined. "Nothing happens" is as valid a consequence as anything else. However, it's usually "nothing happens right away": deallocating an invalid memory block may have severe consequences in subsequent calls to the allocator.