Re:Teaching C
by robotresearcher on Tuesday May 10, 2016 @09:36PM
(#11672048)
Has anyone ever seen any behaviour other than a segfault in the wild, though? Would any real-world compiler author decide that some other behaviour was reasonable? I can't imagine making that decision myself.
[ Parent
| on HN ]
Re:Teaching C
by TorKlingberg on Wednesday May 11, 2016 @05:33AM
(#11673825)
A classic problem is code like this:
printf("a=%p *a=%d", a, *a);
if (a == NULL) return;
An optimizing compiler will likely remove the NULL check completely because the printf above it has undefined behavior if a is NULL.On some microcontrollers I know a pointer to address 0 really is just that. I tested compiling the following
unsigned short *a = 0;
((void (*)(void))a)();
which may cause a jump to address 0 (usually the reset vector).On R8C with the NC30 compiler there are no warnings and the output is:
MOV.W:Q #0H, -2H[FB]
MOV.W:G -2H[FB], R0
MOV.W:Q #0H, R2
JSRI.A R2R0
It jumps to 0. But on PIC 16 with the XC compiler a warning is emitted warning: (1471) indirect function call via a NULL pointer ignored and the statement is not compiled at all.On BSD on the VAX, address 0 used to happen to hold 0, so dereferencing NULL got you zero. That was at the time a sufficiently popular platform that some programs assumed the behaviour (eg, that a null pointer could be used as an empty string), and you can still find older docs on the web exhorting the reader to avoid "all the world's a VAX" syndrome.
I think on DOS in real mode address 0 was not special. Some(?) compilers would add code to programs to check that location on program exit to see if its value had changed and emit an error.
(I think I read about this somewhere, but it was a while ago, and I never really programmed for DOS (well, one little program to set the serial port to some specific settings, but that was about ten lines including whitespace and a little comment explaining what the code did).)
Re:Teaching C
by Kristine1975 on Wednesday May 11, 2016 @03:03AM
(#11673150)
On MacOS Classic (no memory protection) you can happily write to address zero and replace whatever is stored there (I think Apple wisely left that memory address unused, though).