B. Lee
B. Lee

Reputation: 191

Usage of automatic allocation with variable size (alloca) unexplained in literature

I'm reading Fundamentals of Embedded Software - Where C and Assembly Meet (2001), and was presented the following code:

FILE *OpenFile(char *name, char *ext, char *mode)
{
    int size = strlen(name) + strlen(ext) + 2;
    char *filespec = (char *) alloca(size);
    sprintf(filespec, "%s.%s", name, ext);
    return fopen(filespec, mode);
}

The author does not clarify why alloca is useful, or what it achieves. He claims "most common reason to allocate dynamic memory from the heap is for objects whose size is not known until execution time..."

However, I don't see why he couldn't just write char *filespec = (char *) size; at line 4.

Upvotes: 1

Views: 138

Answers (2)

ArekBulski
ArekBulski

Reputation: 5078

alloca allocates on the stack, which means it will be deallocated after function ends, no manual free required. malloc allocates on the heap and requires manual release. These two functions are fundamentally different. (You did not ask about malloc but I presume you might be.)

Also explicit casting that you describe does not do any allocation either, it just makes a cast that does not make any sense as far as I can tell. That casting would not make code correct.

Upvotes: 1

dune.rocks
dune.rocks

Reputation: 517

Don't use alloca in your programs these days please :-) It's not the same as (char *) size! It's the same as char filespec[size], but he'll have used it because VLA's (variable-length arrays) were probably not available in his compiler (they came in C99 and you should use them) in addition to probably not having access to the heap in the embedded application.

Upvotes: 3

Related Questions