1
 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)"

Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5fc00730 0x00007fff8db20bcb in __svfscanf_l ()

What can cause this ?? I looked into *fp in gdb. before reading totalRun _offset = 0 and after reading _offset = 4096. content of totalRun was correct ("3"). I only read one line and why is offset 4096? Also what is _blksize referring to in FILE.

Thank you

4

2 回答 2

2

您需要为 分配内存model,它是一个未初始化的指针。还要确保fscanf()不会读取超出分配给的数组model。如果model不需要动态分配,则只需使用本地数组。例如:

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

始终检查 的返回值,它返回成功分配的数量,否则如果调用失败fscanf(),程序将处理未初始化的变量。fscanf()

于 2012-10-15T13:13:24.207 回答
1

变量model未初始化。您必须先为其分配内存,然后才能在该fscanf()方法中使用它。您可以通过两种方式进行:

  1. 静态 -char model[1024];
  2. 动态 -完成后char * model = (char*) malloc(1024);不要忘记使用free()释放缓冲区。
于 2012-10-15T13:18:10.833 回答