文献中未解释的可变大小自动分配 (alloca) 的使用

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

我正在阅读 嵌入式软件基础 - C 和汇编相遇的地方 (2001),并看到了以下代码:

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);
}

作者没有阐明 alloca 为什么有用,或者它实现了什么。他声称 "most common reason to allocate dynamic memory from the heap is for objects whose size is not known until execution time..."

但是,我不明白他为什么不能在第 4 行写 char *filespec = (char *) size;

最近请不要在您的程序中使用 alloca:-) 它与 (char *) 大小不同!它与 char filespec[size] 相同,但他会使用它,因为 VLA(可变长度数组)可能在他的编译器中不可用(它们出现在 C99 中,你应该使用它们)除了可能无法访问到嵌入式应用程序中的堆。

alloca allocates on the stack, which means it will be deallocated after function ends, no manual free required. malloc 在堆上分配,需要手动释放。这两个功能是根本不同的。 (你没有问过 malloc,但我想你可能会问。)

此外,您描述的显式转换也不进行任何分配,它只是进行了一个据我所知没有任何意义的转换。该转换不会使代码正确。