yasar
yasar

Reputation: 13758

alloca over variable length arrays for character buffer

Consider this code (error checking removed for brevity):

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

This code allocates memory on stack for buffer (if I am not misunderstanding something.) There is also alloca() function which I could have used for same purpose (I guess). I was wondering if there were any reason why I would want to choose one over other?

Upvotes: 1

Views: 121

Answers (2)

valdo
valdo

Reputation: 12941

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 ?

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490573

You'd generally want to use a VLA as you have above, because it's clean and standard, whereas alloca is ugly and not in the standard (well, not in the C standard, anyway -- it probably is in POSIX).

Upvotes: 2

Related Questions