HP OpenVMS Systems

ask the wizard
Content starts here

Question for C Standards Committee?

» close window

The Question is:

A philosophical question. Malloc() allocates memory on the heap. But there is
 as far as I know no equivalent function to allocate memory on the stack as for
 example for array abc in
  char	abc[SIZE];
when SIZE is not known until run-time.
Why not? The advantage would be automatic deallocation upon function return
 thereby eliminating the need to manually deallocate and the risk of forgetting
 to free the memory.
Thank you very much.

The Answer is :

  You will want to direct your question to the C standards body, as
  there is no C standards compliant mechanism for this.  C++ attempts
  to address some of the omissions in the C model, and particularly
  in this case with the C++ concepts of constructors and destructors
  and such.
  Some C compiler implementations do provide an alloca() mechanism,
  Compaq C has the __ALLOCA built-in function and the asm directive
  (direct manipulation of the stack pointer) for those programmers
  wishing to create platform-specific coding.
  As is the case with stack-based memory allocations such as
  function-local variables, you must exercise care with alloca-based
  memory allocations.  Should references to the stack-based memory
  area "outlive" the validity of the stack frame itself, various
  corruptions can ensue.
  C memory management itself is inherently rather generic in nature,
  and thus can be ill-suited for certain applications.  (The RTL VM
  services underlying the C malloc() and free() calls do attempt to
  learn the application memory access patterns.)
  If you wish to manage your own memory, you can also use VM zones
  for this purpose, and take full control over the lookaside list
  sizes and other attributes.  Further, you can designate (within
  your application) one VM zone as a temporary memory zone, and flush
  the entire zone when, for instance, the program is ready to prompt
  for a new user command; when all temporary memory utilized by the
  last command processed can be safely freed.
  Also please see topic (6811).

answer written or last revised on ( 30-JUL-2001 )

» close window