fwrite分段错误 - 4字节大小的无效读取

3

这让我疯狂,所以任何帮助都将不胜感激。

我正在开发一个程序,用于扫描Wi-Fi接入点并使用不同的功能进行管理。其中之一是将接入点列表保存到文件中,另一个是从文件中读取接入点并将它们添加到当前列表中。 接入点存储在链表中,其中“p”包含一个接入点的信息(mac、模式、加密、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

对于所有部分都是一样的。通过十六进制编辑器分析文件输出,我可以看到数据已经被正确存储。

这是read函数中有问题的部分:(我读取了第一个字符[包含在文件中的接入点数量]并将其存储以便稍后转换为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-check=full --show-reachable=yes --track-origins=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; - Kerrek SB
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
        ^^^
这是一个重要的提示,即在执行fread时,fp可能为NULL。您在fopen时是否进行了检查?请注意这一点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接