简体   繁体   English

fscanf()seg fault程序接收信号EXC_BAD_ACCESS

[英]fscanf() seg fault Program received signal EXC_BAD_ACCESS

  16 char* input = (char*) argv[1]; 17 FILE *fp = fopen (input, "r"); 18 if( fp == NULL) 19 { 20 printf(" reading input file failed"); 21 return 0; 22 } 23 fseek(fp,0,SEEK_END); 24 int file_size = ftell(fp); 29 rewind(fp); 30 int i; 31 int totalRun; 32 char * temp; 33 char* model; 34 char* example; 36 fscanf(fp,"%d",&totalRun); 37 fscanf(fp,"%s",model); 

Above is my code I get this error at line 37 "fscanf(fp,"%s".model)" 上面是我的代码我在第37行“fscanf(fp,”%s“.model)得到此错误”

Program received signal EXC_BAD_ACCESS, Could not access memory. 程序收到信号EXC_BAD_ACCESS,无法访问内存。 Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5fc00730 0x00007fff8db20bcb in __svfscanf_l () 原因:KERN_PROTECTION_FAILURE位于地址:0x00007fff5fc00730 0x00007fff8db20bcb in __svfscanf_l()

What can cause this ?? 什么能导致这个? I looked into *fp in gdb. 我查看了gdb中的* fp。 before reading totalRun _offset = 0 and after reading _offset = 4096. content of totalRun was correct ("3"). 在读取totalRun _offset = 0之前和读取_offset = 4096之后.totalRun的内容是正确的(“3”)。 I only read one line and why is offset 4096? 我只读了一行,为什么偏移4096? Also what is _blksize referring to in FILE. 还有什么是_blksize在文件中引用。

Thank you 谢谢

You need to allocate memory for model , it is an uninitialised pointer. 你需要为model分配内存,它是一个未初始化的指针。 Also ensure fscanf() does not read beyond the array assigned to model . 还要确保fscanf()不会超出分配给model的数组。 If model does not need to by dynamically allocated then just use a local array. 如果model不需要通过动态分配,那么只需使用本地数组。 For example: 例如:

char model[1024];
if (1 == fscanf(fp, "%1023s", model))
{
}

Always check the return value of fscanf() , which returns the number of successful assignments, otherwise the program will be processing uninitialised variables if the call to fscanf() fails. 始终检查fscanf()的返回值,它返回成功分配的数量,否则如果对fscanf()的调用失败,程序将处理未初始化的变量。

The variable model is not initalized. 变量model不是初始化的。 You must allocated memory for it before it can be used in the fscanf() method. 必须先为它分配内存,然后才能在fscanf()方法中使用它。 You can do in two ways: 你可以用两种方式做:

  1. Statically - char model[1024]; 静态 - char model[1024];
  2. Dynamically - char * model = (char*) malloc(1024); 动态 - char * model = (char*) malloc(1024); Don't forget to use free() to deallocate the buffer once you are done. 一旦完成,不要忘记使用free()来释放缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM