1

考虑这段代码(为简洁起见,删除了错误检查):

int main()
{
        int fd, nread;
        struct stat st_buff;

        /* Get information about the file */
        stat("data",&st_buff);
        /* Open file data for reading */
        char strbuff[st_buff.st_blksize];
        fd = open("data",O_RDONLY);

        /* read and write data */
        do {
                nread = read(fd,strbuff,st_buff.st_blksize);
                if (!nread)
                        break;
                write(STDOUT_FILENO, strbuff, nread);
        } while (nread == st_buff.st_blksize);

        /* close the file */
        close(fd);

        return 0;
}

这段代码在堆栈上为缓冲区分配内存(如果我没有误解的话。)还有alloca()我可以用于相同目的的函数(我猜)。我想知道是否有任何理由让我想选择一个而不是另一个?

4

2 回答 2

2

您通常希望像上面那样使用 VLA,因为它干净且标准,而alloca丑陋且不在标准中(好吧,无论如何,不​​在 C 标准中-它可能在 POSIX 中)。

于 2012-04-23T17:05:37.370 回答
0

I'm pretty sure both are the same at machine-code level. Both take the memory from the stack. This has the following implications:

  1. The esp is moved by an appropriate value.
  2. The taken stack memory is probe'd.
  3. The function will have to have a proper stack frame (i.e. it should use ebp to access other locals).

Both methods do this. Both don't have a "conventional" error handling (raise a SEH exception in Windows and whatever on Linux).

There is a reason to choose one over another if you mind about portability. VLAs are not standard IMHO. alloca seems somewhat more standard.

P.S. consider using malloca ?

于 2012-04-23T17:11:16.717 回答