David Ranieri
David Ranieri

Reputation: 41026

VLA's memory available under gcc

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

Upvotes: 0

Views: 236

Answers (3)

Art
Art

Reputation: 20402

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.

Upvotes: 2

ouah
ouah

Reputation: 145899

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.

Upvotes: 1

Aniket Inge
Aniket Inge

Reputation: 25725

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

Upvotes: 1

Related Questions