3 ms·
You can check for errors with alloca. It returns NULL on failure. You have the same problem as with error checking malloc. On platforms with overcommit (any for
by derf_ 8y ago
You can check for errors with alloca. It returns NULL on failure. You have the same problem as with error checking malloc. On platforms with overcommit (any fork-based UNIX, except maybe Solaris) it doesn't fail at allocation time, it fails when you try to access the memory and fail to map a page. But at least on 32-bit systems it can detect when you exhaust your address space (an actual problem for things like web browsers that still commonly ship 32-bit binaries and use lots and lots of threads).
But yeah, the real reason is that MSVC will never implement VLAs.
- CJefferson 8y agoI worry you are mixing up alloca and malloc. Alloca allocates off the stack. All modern platforms have irritatingly small stack sizes, and if you overflow them your code just defaults with an annoyingly imprecise error. There is no overcommitting with stacks in practice.
- BeeOnRope 8y agoIt returns NULL to indicate errors? Not any platform I've used lately. The Linux man page is in fact explicit that it never returns NULL: RETURN VALUE The alloca() function returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behavior is undefined. NOTES ... The inlined code often consists of a single instruction adjusting the stack pointer, and does not check for stack overflow. Thus, there is no NULL error return. As a practical matter it is difficult for an implementation to have alloca return an error value even if they wanted to: it would be both two slow and in some cases "impossible" to know ahead of time in the same way that malloc is unlikely to return null on some systems.
- nwmcsween 8y agoHow could alloca return NULL? You would have to catch bumping into a guard page would you not?
- codys 8y ago_theoretically_ a C implementation could track the maximum stack size it has allocated, detect would be overflows, and report them. guard pages are one mechanism for doing that.