SIGSEGV with C compiler/RTL. Possible scanf() problem.
Ian Lance Taylor
iant@google.com
Wed Feb 9 05:51:00 GMT 2011
TPCgcc@mklab.ph.rhul.ac.uk writes:
> I have been experiencing variable corruption / SIGSEGV problems with
> some pieces of quite simple code. The exact symptoms are hard to pin down
> and can vary from gcc version to version and whether or not compiler
> optimisation is turned on. Trivial changes to the program can make the
> symptoms come and go. The common factor is a particular scanf() statement.
> Here is an illustration which generates a SIGSEGV when the EOF is read. I
> am entering input data "123.456,55<CR><ctrl-D>" from the keyboard. The
> results are identical if redirecting stdin from a file. Can anyone
> reproduce this error and/or fault my code?
> int main(int argc, char **argv)
> {
> double offset, caltime;
> unsigned int sigbits;
> unsigned char ignore;
>
> offset=0.0;
> while (scanf("%20lf%[,]%u", &caltime, &ignore, &sigbits) != EOF) {
> caltime=caltime-offset;
> printf ("caltime=%lf sigbits=%u\n", caltime, sigbits);
> }
> return 0;
> }
The %[ conversion in scanf takes a pointer to a buffer, not a pointer to
a single character. If you type anything other than precisely a single
comma, scanf will clobber the stack, which is probably why you are
seeing a crash when ^D causes the main function to return.
This question is just about the C language, it doesn't seem to have
anything to do with gcc.
Ian
More information about the Gcc-help
mailing list