user2823910
user2823910

Reputation: 35

Weird output after parsing

I have some weird error now, when scanning a bigger file such as this one:

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

Im a using this code:

 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++; }

The output is good at the beginning but turns out weird starting from the 7th line showing:

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

And from that point, if I add more lines to parse everything it gets weirder and weirder. Am I out of bounds or something?

Upvotes: 1

Views: 93

Answers (1)

chux
chux

Reputation: 153338

Number of issues

  1. Big: Not allocating memory.

  2. Not using the result of sscanf()

  3. Not opening the file in text mode

Suggest:

// 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
}

Upvotes: 1

Related Questions