VLA's memory available under gcc

帅比萌擦擦* 提交于 2020-01-06 08:43:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!