by kibibu · 10y ago · 0 comments
Consider this mini example:
void myfunc (int * p) {
int t = *p;
if(p == NULL) { return;}
*p = t + 1;
}
Accessing p before null check is undefined, and causes compilers to deduce that the null check isn't required. It can therefore be stripped, which most programmers would find very surprising.Edit: yes, the replies are right, I meant to dereference *p rather than just copy the pointer. Fixed and somewhat simplified.
I was trying (badly) to remember this example: http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
struct foo {
int bar;
}
void myfunc(struct foo *p) {
int *t = &p->bar;
if(p == NULL) return;
*t = 5;
}
Is this undefined? Probably. Absent compiler optimizations, it won't cause a crash on any system you're ever likely to encounter because it's not actually dereferencing the pointer, but some versions of gcc have caused security issues in Linux by optimising away NULL checks like this. ...
void myfunc(struct foo *p) {
int *t = (int *)((char *)p + offsetof(p->bar));
...
}
right? In the C abstract machine taking the address of an offset of a pointer is always defined, I think.This is true as dereferencing a NULL pointer is undefined behaviour, so is fair game for optimizations. The compiler may assume that NULL pointer dereferencing results in a trap/segfault and that the conditional can never be executed.
If I am wrong, and your example actually exhibits undefined behaviour, I would certainly love to learn why.
Edit: I'm a moron, thanks for pointing out the obvious to me :)
Your example is plain wrong.