1

我现在有一些奇怪的错误,当扫描一个更大的文件时,比如这个:

  1. 0x1001 0x0001
  2. 0x1001 0x0002
  3. 0x0004
  4. 0x0005
  5. 0x0005
  6. 0x0005
  7. 0x0005
  8. 0x0007 0x0001

我正在使用此代码:

 int *inst = (int*)malloc(sizeof(int));
 int *op1 = (int*)malloc(sizeof(int));

 FILE *fp = fopen(argv[1], "r");
 char line [32]; // Max line size
 int count=0;

while(fgets (line, sizeof(line),fp) != NULL){
    sscanf(line, "%x" "%x", &inst[count], &op1[count]);
    printf("0x%x 0x%x\n", inst[count],op1[count]);
    count++; }

输出在开始时很好,但从第 7 行开始变得很奇怪:

  1. 0x1001 0x1
  2. 0x1001 0x3
  3. 0x4 0x0
  4. 0x5 0x0
  5. 0x5 0x0
  6. 0x5 0x0
  7. 0x5 0x241
  8. 0x1007 0x0

从那时起,如果我添加更多行来解析所有内容,它会变得越来越奇怪。我是不是越界了?

4

1 回答 1

1

问题数量

  1. Big:不分配内存。

  2. 不使用结果sscanf()

  3. 不以文本模式打开文件

建议:

// Instead of 8, make 2 passes to find the number of lines or reallocate as you go.
int *inst = calloc(8, sizeof(*inst));  /
// calloc initializes to 0, nice as your various lines don't always have 2 numbers.
int *op1 = calloc(8, sizeof(*op1));
FILE *fp = fopen(argv[1], "rt");
...
int result = sscanf(line, "%x" "%x", &inst[count], &op1[count]);
switch (result) {
  case 1: printf("0x%x\n", inst[count]); break;
  case 2: printf("0x%x 0x%x\n", inst[count],op1[count]); break;
  default: ; // handle error
}
于 2013-09-27T16:29:36.613 回答