2011-11-25 26 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编辑它?