3 ms·
One of the main issue is no error checking on this kind of "allocation" (it's the same as alloca()). This issue also somehow exists with a fixed size buffer, bu
by ux 8y ago
One of the main issue is no error checking on this kind of "allocation" (it's the same as alloca()). This issue also somehow exists with a fixed size buffer, but at least you get a much more predictable outcome (you have full control on the stack usage, unless you have a user controlled recursion).
- derf_ 8y agoYou 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.
- codys 8y ago> you have full control on the stack usage, unless you have a user controlled recursion IMO, the reality with C is that one needs to be aware of input, whether using VLAs, recursion, or any number of other mechanisms (overflowing calculated values passed to malloc, etc). It isn't clear that VLAs are a significant departure from what C already provides in the way of unsafety.