Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

heap memory - Is it required that a C Variable Length Array is allocated from the stack?

After removing all the calls to malloc and calloc from our code for an embedded system, I was surprised to find that malloc was still being linked in. The call graph pointed me to a function which had no explicit *alloc calls, and no calls to any library functions that might allocate, like strdup.
I had to look at the generated assembly to realize that it was due to an inlined function which contained a VLA.

I thought VLAs had to be stack-allocated. Is this compiler broken?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no requirement that VLAs be allocated from the stack (the language standard doesn't even mention stacks or heaps). The only requirement is as follows:

6.2.4 Storage durations of objects
...
7 For such an object that does have a variable length array type, its lifetime extends from the declaration of the object until execution of the program leaves the scope of the declaration.35) If the scope is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate.
35) Leaving the innermost block containing the declaration, or jumping to a point in that block or an embedded block prior to the declaration, leaves the scope of the declaration.

Given this, it makes sense to allocate from the stack, but for very large objects this may not be possible, and such an object may be allocated from the heap or some other memory segment instead. The bookkeeping is up to the implementation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...