2012-04-23 55 views
1

考慮以下代碼的可變長度陣列(誤差爲簡潔檢查刪除):ALLOCA超過用於字符緩衝器

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()函數,我可以用於相同的目的(我猜)。我想知道爲什麼我會選擇一個而不是其他的理由?

回答

2

你一般都想像上面那樣使用VLA,因爲它乾淨而標準,而alloca很醜並且不在標準中(好吧,不是在C標準中,無論如何 - 它可能在POSIX中)。

0

我很確定這兩者在機器碼級別是一樣的。兩者都從堆棧中獲取內存。這具有以下含義:

  1. esp被移動一個適當的值。
  2. 採取的堆棧內存爲probe'd。
  3. 該函數將必須有一個適當的堆棧框架(即它應該使用ebp來訪問其他當地人)。

這兩種方法都是這樣做的。兩者都沒有「常規」錯誤處理(在Windows和Linux上引發SEH異常)。

如果你介意可移植性,有一個選擇另一個的理由。 VLA不是標準的恕我直言。 alloca似乎有點更標準。

P.S.考慮使用malloca

+0

我不知道malloca,但我想這是Windows的東西吧?我的圖書館似乎沒有找到malloca。 – yasar 2012-04-23 17:21:43