4 ms·
All C compilers I know either have VLA or alloca. In one of my projects, a bit of macro magic uses either VLA or alloca to generate a temporary array. Works gre
by jpfr 7y ago
All C compilers I know either have VLA or alloca.
In one of my projects, a bit of macro magic uses either VLA or alloca to generate a temporary array. Works great! I don't have further requirements here.
Please explain what you mean by "safe" in this context.
- enriquto 7y agoI mean a way to control for stack overflow. I would like to allocate very large images as VLA, where the size is only known at runtime. If I malloc a too large image, the systems asks for more memory or malloc fails. If I declare a VLA too large, it fails silently in an unrelated part of my program due to stack corruption.
- devit 7y agoCorrect implementations use stack probing (access one word for every page in the allocation) to guarantee that a stack overflow happens immediately rather than resulting in stack corruption.
- enriquto 7y agoAlright, but that doesn't really solve anything, does it? It just makes the problem easier to debug.
- thenewnewguy 7y agoWhat's the problem, that the stack is capable of being overflowed? How do you expect the C compiler to fix that?
- enriquto 7y agoThe stack is not a concept belonging to the C language definition, it is just an implementation choice made by some compiler vendors (all that I know of). The semantics for VLA are clear and very useful. I would certainly not expect that the memory for VLA is implemented on the same stack as the function call stack. My complain for C programming (what I called its "tragedy") is that no compiler provides a mechanism for safely using all available memory via VLA. Edit: you may answer: "use alloca then". But the syntax for alloca is not that convenient, and the semantics are very different. A common use for VLA is to declare a temporary array inside the body of a loop, this is not possible with alloca.
- gmueckl 7y agoWhat platform are you on that cannot detect a stack overflow?
- enriquto 7y agoI do not know how to do it on any platform. My problem is this: void f(int n) { float t[n]; // what do I write here to check if everything is OK ? ... }
- dmitrygr 7y agoModern gcc handles this very well actually. Here: https://gcc.gnu.org/onlinedocs/gccint/Stack-Checking.html https://gcc.gnu.org/onlinedocs/gccint/Stack-Checking.html
- pm215 7y agoI used to work on a (now defunct) RTOS whose C runtime didn't support alloca. Functions were all compiled down to a portable bytecode representation that had to statically declare the stack usage, so there was no way to have a function with variable stack size. Not having a real alloca was occasionally an issue for porting C code to it (but less annoying than not having fork()).