I had this argument with some people saying that C out-of-bound pointers cause undefined behavior even if they're not being dereferenced. example:
int a;
int *p = &a;
p = p - 1;
the third line here will cause undefined behavior even if p
is never dereferenced (*p
is never used).
In my opinion, it sounds illogical that C would check if a pointer is out-of-bound without the pointer being used (it's like someone would inspect people on the street to see if they're carrying guns in case they enter his house. Where the ideal thing to do is to inspect people when they're about to enter the house). I think if C checks for that then a lot of runtime overhead will occur.
Plus, if C really check for OOB pointers then why this won't cause UB:
int *p; // uninitialized thus pointing to a random adress
in this case why nothing happen even if the chance of p
pointing to an OOB adress is high.
ADD:
int a;
int *p = &a;
p = p - 1;
say &a
is 1000. Will the value of p
after evaluating the third line be:
- 996 but still undefined behavior because
p
could be dereferenced somewhere else and cause the real problem. - undefined value and that's the undefined behavior.
because I think that "the third line was called to be of undefined behavior" in the first place was because of the potential future use of that OOB pointer (dereferencing) and people, over time, took it as an undefined behavior in it's own. Now, is the value of p
will be 100% 996 and that still undefined behavior or its value will be undefined?