Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - What's the difference between alloca(n) and char x[n]?

What is the difference between

void *bytes = alloca(size);

and

char bytes[size];  //Or to be more precise, char x[size]; void *bytes = x;

...where size is a variable whose value is unknown at compile-time.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

alloca() does not reclaim memory until the current function ends, while the variable length array reclaims the memory when the current block ends.

Put another way:

void foo()
{
    size_t size = 42;
    if (size) {
        void *bytes1 = alloca(size);
        char bytes2[size];
    } // bytes2 is deallocated here
}; //bytes1 is deallocated here

alloca() can be supported (in a fashion) on any C89 compiler, while the variable length array requires a C99 compiler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...