GCC (Ubuntu 4.1.2-0ubuntu3) Causing Data Corruption
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
gcc-defaults (Ubuntu) |
Invalid
|
Undecided
|
Unassigned |
Bug Description
Binary package hint: gcc
Updated Feisty install as of 2007-02-26 (upgraded from Edgy). Noticed this strange behavior with GCC 4.1.2 today:
(test.txt is a text file containing a single digit, zero in this case).
<code>
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c = 'a';
const char d = '6';
FILE *f = NULL;
if((f = fopen("test.txt", "r")) == NULL) {
fprintf(stderr, "Error opening file!\n");
return EXIT_FAILURE;
}
printf("d = %c\n", d);
printf("d = %d\n", atoi(&d));
atoi(&c);
c = fgetc(f);
printf("d = %c\n", d);
printf("d = %d\n", atoi(&d));
fclose(f);
return 0;
}
</code>
Should output:
d = 6
d = 6
d = 6
d = 6
Actual results:
d = 6
d = 6
d = 6
d = 60
It is interesting because test.txt contains only the digit zero, and 60 is output instead of 6. When change to 1...9 the 6 is always followed by the same digit as in the text file.
GCC 3.3 does not exhibit this behavior on the same system.
Hi,
the output of
printf("d = %d\n", atoi(&d));
is 100% undefined
You're casting a char to a null terminated string.
The compiler do whatever it wants with the stack, variables order, registers and so on.