0

I'm writing a library in which I've found the non-standard C function alloca to be really useful. Several sources (linux man pages, this SO question) caution against using alloca. Unlike malloc and friends, which are supposed to return NULL when you run out of heap memory, using alloca is undefined behavior in the event of a stack overflow. In my case, I have hard limits (enforced by plenty of assert statements) on the sizes of the objects I'm allocating, so I think that this completely sensible caveat isn't an issue.

Nonetheless, I don't see why alloca necessarily has to result in undefined behavior in this circumstance. Why couldn't alloca check where the stack pointer is and return NULL in the event of a possible stack overflow? Implementing these checks would of course be platform- and architecture-specific, but I don't see why it should be impossible.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Daniel Shapero
  • 1,869
  • 17
  • 30
  • 1
    `alloca` is outdated. If you need a variable length array, use VLAs. But take note of their possibly different lifetime. That does not take the responsibility from you toensure enough stack is available, though. – too honest for this site Jun 28 '17 at 02:37
  • 1
    `alloca()` _could_ return `NULL` in order to prevent a stack overflow. It is not a standard C library function and there is insufficient call for to include it with your desired functionality. It is not that it is impossible, it is lack of interest. Note C does not even require a _stack_. – chux - Reinstate Monica Jun 28 '17 at 03:41
  • alloca does have its uses, But it does not check for a possible stack overflow, which can lead to undefined behaviour. – Michaël Roy Jun 28 '17 at 04:40

0 Answers0