Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

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.

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()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top