问题
As malloc returns NULL, is there any way to detect that there is insufficient memory on the stack using VLA's?
回答1:
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.
回答2:
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.
回答3:
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()
来源:https://stackoverflow.com/questions/15131941/vlas-memory-available-under-gcc