Take the 2-minute tour ×

As malloc returns NULL, is there any way to detect that there is insufficient memory on the stack using VLA's?

share|improve this question
a stack fault comes to mind. If you think the number may be unreasonable, don't gamble; use malloc() –  WhozCraig Feb 28 '13 at 9:32
"If you have to ask, you can't afford it." –  R.. Feb 28 '13 at 14:22

3 Answers 3

up vote 1 down vote accepted

There is nothing in C to guarantee the success of declaring a VLA or checking for failure regarding memory usage. This is the same for any declaration of an automatic object, VLA or not.

share|improve this answer
Thanks for your answer, what's the behaviour when there is not enough space for store automatic objects? the program doesn't start because required space is know at runtime? it start but crashes? (Excuse my poor english) –  Alter Mann Feb 28 '13 at 10:09
@DavidRF usually it starts to crash (segmentation fault for example) soon after entering into the function, after the declaration of the object. But it may do anything as we are in the realm of undefined behavior. –  ouah Feb 28 '13 at 10:12

You can hope for a crash, but the worst case scenario is that things will seem to work and you'll end up writing to some other memory. At least gcc by default doesn't generate code that makes an attempt to verify that the memory is available (there's an option for it though), so a large enough VLA can end up anywhere. On MacOS you only need a 0.5MB VLA in a threaded process to accidentally end up writing to the stack of some other thread. 10MB on Linux.

If you can't guarantee that a VLA is small (less than a page or two) don't use it.

share|improve this answer

malloc() checks the heap, VLAs work on increasing the stack size. if malloc() returns NULL chances are your stack has been filled too.

As WhozCraig points out, do not gamble with VLAs. If the array size is big - use malloc()

share|improve this answer

Your Answer


