2013-10-04 32 views
0

我感到困惑的malloc和free的使用,這裏是我的榜樣,代碼:使用的malloc和free:無效的下一個尺寸誤差

需要明確的是,假設我們想從文件中讀取行並寫入一個數組。該文件的格式是:

3 
abc 
def 
ghi 
jkl 
mno 
pqr 

我想將前三行存儲到array1中,並將其餘的數組放入數組2中。

的代碼:

int num; 

FILE *fin = fopen("filename", "r"); 

/*Read the first line of the file*/ 
fscanf (fin, "%d", &num); 

char **array1 = malloc(sizeof(char *) * num); 
char **array2 = malloc(sizeof(char *) * num); 

/*Apply sizeof(num * num) memory blocks and set the first address to array1[0]*/ 
array1[0] = malloc(sizeof(char) * num * num); 
array2[0] = malloc(sizeof(char) * num * num); 

/*Allocate the address of each (char *) array pointer*/ 
int i; 
for (i = 0; i < num-1; i++) 
{ 
    array1[i+1] = array1[i] + num; 
} 

for (i = 0; i < num; i++) 
{ 
    fscanf(fin, "%s", array1[i]); 
} 

調用free函數時,就會出現問題:

/*ERROR: free(): invalid next size (fast): 0x0804b318(gdb)*/ 
free(array1[0]); 
free(array1); 

由於地址0x0804b318是ARRAY1 [0],我想分配可能不夠的存儲器塊。爲了使其更大:

array1[0] = malloc(sizeof(char) * (num+1) * (num+1)); 

和它的工作,但我很困惑這個,因爲文件的第3行是:

abc 
def 
ghi 

malloc函數返回一個指向3 * 3個char數組,足夠存儲
這3行,爲什麼我們需要(3 + 1)*(3 + 1)?

+1

[請不要在C]中輸入'malloc()'的返回值(http://stackoverflow.com/a/605858/28169)。 – unwind

+0

謝謝,我會編輯它。 – fishiwhj

回答

4

字符串存儲與終止'\0'-字符,也需要空間。因此,要存儲3個字符的字符串,需要4個字符的空間。

+0

其他方法是,不要讀取'\ 0'。 – icbytes

相關問題