Re: alloca / _alloca / dynamic stack memory



Michael Crawley <MichaelCrawley@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
Dynamic stack allocation is nice for performance tuning. If an
object is going to be short-lived and is very small, it would be
ideal to not allocate memory from a lock-based memory allocator like
malloc(size_t)

So at this point, why not declare it as a local variable?

Even if you succeed in your endeavor, imagine the user's surprise when
this innocent-looking code breaks:

MyObj* factory() { return new MyObj; }

MyObj* p = factory();
// Do something to p
delete p;

Of course since MyObj was allocated on the stack inside factory, the
memory is reclaimed as soon as factory() returns (without running
MyObj's destructor, to boot). The rest of the code cheerfully works with
garbage.


Can you show a use case where implementing operator new as _alloca might
be beneficial?
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925


.



Relevant Pages

  • Re: obj function hello()
    ... Obj* myobj = malloc; ... myobj is a *pointer* - you want enough memory for myobj to point ... not however much memory the pointer takes up. ... i have to allocate memory for myobj not the pointer it self ...
    (comp.lang.c)
  • Tru64 issues with Infinite limits
    ... An automated test in my nightly build was failing due to Out of Memory ... Cannot allocate block 146 ...
    (comp.unix.tru64)
  • Re: run-time vs compile-time
    ... > offset related to some location (like stack base) somewhere. ... > offset from heap to pi. ... When you allocate an int on the heap, it is allocated at address 1. ... application has a given amount of memory it can use as it wishes. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: run-time vs compile-time
    ... > offset related to some location (like stack base) somewhere. ... > offset from heap to pi. ... When you allocate an int on the heap, it is allocated at address 1. ... application has a given amount of memory it can use as it wishes. ...
    (comp.lang.cpp)
  • Re: Sharing memory between kernelspace and userspace
    ... deallocate, on a totally dynamic basis, userspace ... Let userspace allocate shared memory visible to multiple ... and pass that into the kernel for it to write to. ...
    (Linux-Kernel)