2014-01-25 247 views
0

我已經編寫了一個程序,它將MB的值作爲3參數,併爲我提供了吞吐時間。緩衝區NULL!:無法分配內存

int main(int argc,char* argv[]){ 
double kb = 0; 
int time_taken = 0; 
double throughput = 0; 
int i = 0; 
int w_rw = 0; 
int fd = -1; 
int bw = -1; 
unsigned long long nob = 0; 
char ip; 
char* file_name = "myfile"; 
char* buff; 
struct stat info; 
struct timeval start_time,end_time; 
int mb = 1024 * 1024; 

/* Check the nos for W/RW and MBs*/ 
if(1 == argc){ 
     printf("\n Missing 2 params R/RW & MB,Eg: execute ./a.out 2 100 \n"); 
     return 1; 
} 
if(argc < 4){ 
     w_rw = atoi(argv[1]); 
     if(w_rw > 2){ 
       w_rw = 2; 
     } 
     nob = (atoi(argv[2]) * mb); 
     printf("\n W/RW : %d BYTES : %u \n",w_rw,nob); 
} 
else{ 
     // Do Nothing 
} 
/* Allocate Buffer */ 
buff = (char *)malloc(nob * sizeof(char)); 
if(NULL == buff){ 
     perror("Buffer NULL!"); 
     return -1; 
} 

printf("\n File - Create,Open,Write,Close \n"); 

for(i = 0; i < w_rw; i++){ 
     if(i == 0){ 
       printf("\n --- Write IO Performance--- \n"); 
     } 
     else{ 
       printf("\n --- Re-write IO Performance--- \n"); 
       printf("\n Press any char to continue : \n"); 
       ip = getchar(); 
     } 

     /* Open file*/ 
     if((fd = open(file_name,O_CREAT | O_RDWR))< 0){ 
       perror("Open failed!"); 
       return -1; 
     } 

     /*Calculating the start and end time of write*/ 
     gettimeofday(&start_time,NULL); 
     if((bw = write(fd,buff,nob)) < 0){ 
       perror("Write failed!"); 
       return -1; 
     } 
     gettimeofday(&end_time,NULL); 

     /*Calculating the throughput*/ 
     time_taken = (end_time.tv_sec - start_time.tv_sec); 
     kb = bw/1024; 
     throughput = kb/time_taken; 

     /* Start */ 
     if(-1 == stat(file_name,&info)){ 
       perror("STAT Failed"); 
       return -1; 
     } 

     printf("\n Inode no: %d \n Blocks : %d \n",info.st_ino,info.st_blocks); 
     printf("\n Start sec : %u \n",start_time.tv_sec); 
     printf("\n End sec : %u \n",end_time.tv_sec); 
     printf("\n Bytes written : %d bytes \n",bw); 
     printf("\n Time_taken : %d secs \n",time_taken); 
     printf("\n Throughput : %f kb/sec \n",throughput); 

     close(fd); 
} 

unlink(file_name); 
return 0; 
} 

O/P:

[根@ RW GFS]#./a.out 2 76800

W/RW:2字節:3221225472 緩衝NULL!:無法分配存儲器

+0

取決於您的系統。 –

+0

更好地使用'size_t'來處理與分配有關的任何事情。 –

+0

另外,不要投「malloc」的結果:https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc –

回答

2

您正在請求一個巨大的內存塊(78GB!)和malloc失敗,如任何標準(臺式機/筆記本電腦)計算機上的預期。

事實上,你必須:

int mb = 1024 * 1024; 
// ... 
nob = (atoi(argv[2]) * mb); 
// ... 
buff = (char *)malloc(nob * sizeof(char)); 

所以nob你的情況1024 * 1024 * 76800

嘗試一個較小的尺寸,它會工作。

+0

但我需要測試大約100G的大尺寸。我有2TB容量的文件系統。爲什麼我不能創造這麼大的尺寸?無符號整型和有符號整數是否重要 – Angus

+4

不是。問題是**你要求78GB的RAM **。我強烈懷疑你有超過78GB的RAM,或者你的電腦可以在虛擬內存中處理78G。你可以通過分配一個緩衝區來實現你的目標,這個緩衝區的大小是要求的一個合理的約數(比如說32MB),然後用'for'循環寫入'n'次。 –