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
431 views
in Technique[技术] by (71.8m points)

c - Is it a good idea to use C99 VLA compared to malloc/free?

Is it a good idea to use C99 VLA? When is it appropriate to use VLA compared to malloc/free? (since VLA may blow up stack?)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, except in cases where you know your stack can blow up. You can also change the size of the stack if necessary, it's different how on every OS but it's possible. The advantages of VLA are:

  • Fast : adjusting the stack pointer and/or the frame pointer would have been done anyway so the cost of a VLA is nearly 0.

  • Easy : a simple definition, no pointer to initialize, to check to free and no risk of memory leaks.

  • It's automatically thread safe as each thread has its own stack. It has also better scaling as there's no need of locking, one problem that can arise when using malloc/free.

  • Readable : it's really a simple concept, so less likely to introduce subtle bugs.

It has some drawbacks:

  • Size limited : as already said, the stack can blow up.

  • Buffer overflows are a bit more serious than on heap memory (one can argue that it's an advantage, as a crashing application is better than a one silently corrupting data and eventually crashing on unrelated instructions).

  • Portability : not all compilers implement it, but it can often be simulated by alloca (attention the semantic is a little bit different but nothing really serious).


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

...