Skip to content

Comment on What Every C Programmer Should Know About Undefined Behavior #1/3parent

Comments

If the compiler can optimize that away, what's the proper method for checking p?

Check p before using it. The issue is when you have code like the following, where the behavior of the first statement is only defined when the condition in the second is false:

    int x = *p;
    if (p == NULL) {
      // p can't be NULL without having triggered
      // undefined behavior in the first line, so
      // this code is removed by the compiler.
      return;
    }
    // ...
The fix is to stop dereferencing p before you know whether it's NULL or not:
    if (p == NULL) {
      // Moving the check before the dereference
      // avoids undefined behavior and resolves
      // the issue.
      return;
    }
    int x = *p;
    // ...
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.