2011-11-25 39 views
3

這讓我瘋狂,所以任何幫助將不勝感激。fwrite分段錯誤 - 無效的讀取大小4

我正在開發一個程序,用於掃描Wi-Fi接入點並用不同的功能管理它們。其中之一是將接入點列表保存到文件,另一個是從文件中讀取接入點並將它們添加到當前列表中。 接入點存儲在鏈接列表中,其中'p'包含一個接入點(mac,mode,encrypted,essid等)的信息,'next'是指向下一個節點的指針。

這裏是我使用保存的部分功能:

void store_info_in_file(list l) 
{ 
list aux; 
aux = l; 
FILE *file; 
.. 
.. 
//After opening the file with a name chosen by the user,it traverses 
//the list and with casts to char, saves each part of each access point. 

//Conversion to char to ease storage in a binary file. 

char essid_len = (char)strlen((aux->p).essid); 
char enc = (char)(aux->p).encrypted; //originally an int 

fwrite(&essid_len,1,1,file);//i'm guessing the size is sizeof(char) now 

與同爲所有部件。 用十六進制編輯器分析文件輸出,我可以看到數據已經正確存儲。

這是讀功能的問題部分:(我讀取第一個字符[文件中包含的訪問點的數量]並存儲它以便稍後轉換爲int)。

//new_apns is for later use, when i will fread the rest of the file at once. 
char new_apns; 
////wifi_collector_list.c:1103 
fread(&new_apns,1,1,fp); 

這將導致一個分段故障由於尺寸4. 這裏的一個無效的讀出是輸出爲:

「的valgrind --leak校驗=全--show可到達=是 - 軌道起源= YES ./app」

http://pastebin.com/LAwsCV11

編輯: 我絕對愚蠢的,我曾寫過:

fp = fopen(string,"rb"); 
if(fp != NULL) 
{ 
    //fread here 
} 

,由於某種原因將其改爲:

if(fopen(string,"rb")) 
{ 
    //fread here, so yes, it's null... 
} 
+2

不要投這麼多。投射模糊的錯誤。例如,你不需要說'int a =(int)5;'。 –

+0

使用valgrind +1 –

回答

3
==21328== Invalid read of size 4 
==21328== at 0x40D8F35: fread (iofread.c:43) 
==21328== by 0x804F043: add_info_from_file (wifi_collector_list.c:1103) 
... 
Address 0x0 is not stack'd, malloc'd or (recently) free'd 
     ^^^ 

這是一個巨大的暗示,fpNULLfread的時間。也許你沒有檢查它,當你fopen編輯它?