Reputation: 35
I have some weird error now, when scanning a bigger file such as this one:
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:
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
Reputation: 153338
Number of issues
Big: Not allocating memory.
Not using the result of sscanf()
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