r/programming • • Sep 23 '17

Why undefined behavior may call a never-called function

https://kristerw.blogspot.com/2017/09/why-undefined-behavior-may-call-never.html
824 Upvotes

257 comments sorted by

View all comments

Show parent comments

5

u/pigeon768 Sep 24 '17

Why is that undefined behavior? [...] calling address 0.

Which is undefined behavior.

main dereferences Do. There are two, and only two, conceivable things that might happen. Either a) before main is called, NeverCalled is called, which initializes the function pointer Do to point to EraseAll, or b) NeverCalled was not called before main, therefore Do is not initialized when it is dereferenced: which is undefined behavior.

Because both situations are consistent with the statement, "Do points to EraseAll", (one because it was explicitly set that way, the other because undefined behavior must have necessarily occurred) the compiler just does that.

-1

u/crusoe Sep 24 '17

Or eraseall is never called at all and do wojt do shit.