fscanf out of bounds write
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
glibc (Ubuntu) |
Invalid
|
Undecided
|
Unassigned |
Bug Description
Hi,
I am learning C and had a strange bug when allocating values into some calloc'd memory with fscanf.
Later calls to fscanf would overwrite previously set values to zero. I am using an AMD athlon 64 bit cpu on
a 32bit Fiesty Fawn version of Ubuntu and I think that the std library must be ignoring the type conversion modifier
and just writing a larger type into the memory.
Attached is a simple program called fscanfbug.c which reproduces the problem.
Is this something I should just work around or should this be fixed in glibc?
Thanks,
Alysander
//Number 5
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
int main (int argc, char *argv[]) {
int8_t *numarray = NULL;
FILE *numfile = NULL;
numarray = calloc(10, sizeof(int8_t));
numfile = fopen("
fscanf(numfile, "//Number %"PRId8, &numarray[8]);
fscanf(numfile, "//Number %"PRId8, &numarray[7]);
printf("The 8th number is: %"PRId8"\n", numarray[8]);
printf("The 7th number is: %"PRId8" (shouldn't this be the same as above?) \n", numarray[7]);
fclose(numfile);
free(numarray);
return 1;
}
You need to check the return value of your calls; the second fscanf does not match anything and therefore doesn't assign anything.
//Number 5
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
int main (int argc, char *argv[]) { "calloc" ); fscanfbug. c", "r"); "fopen" );
int8_t *numarray = NULL;
FILE *numfile = NULL;
int ret;
numarray = calloc(10, sizeof(int8_t));
if (! numarray)
perror(
numfile = fopen("
if (! numfile)
perror(
if (fscanf(numfile, "//Number %"PRId8, &numarray[8]) != 1)
printf("First fscanf returned wrong number of elements\n");
if (fscanf(numfile, "//Number %"PRId8, &numarray[7]) != 1)
printf("Second fscanf returned wrong number of elements\n");
printf("The 8th number is: %"PRId8"\n", numarray[8]);
printf("The 7th number is: %"PRId8" (shouldn't this be the same as above?) \n", numarray[7]);
fclose(numfile);
free(numarray);
return 1;
}
if you run this, you will see that it complains at the second fscanf.