c - fwrite 段错误 - 大小为 4 的无效读取

标签 c binary segmentation-fault fwrite fread

这让我发疯,所以我们将不胜感激。

我正在开发一个扫描 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-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...
 }

最佳答案

==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
        ^^^

这是一个巨大的暗示,即 fpfread 时是 NULL。也许您在fopen编辑它时没有检查它?

关于c - fwrite 段错误 - 大小为 4 的无效读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8273635/

相关文章:

c - 使用 C 程序来计算字符、单词、句子、行或以上所有内容。

c - 我的解释正确吗?我可以打印 double 的二进制表示形式,例如 :1?

assembly - 不使用 MOVZX/MOVSX 的汇编中的零/符号扩展

r - 使用 R 中的 glmnet 预测二进制结果的函数

c - 为什么 C 代码会出现段错误?

c - main 之前的段错误

c - strcmp 行为怪异

DMA 上下文中的缓存一致性问题

python - 获取 1 位在 python Long 对象中的位置

C 段错误(Libcapn APNS 库)