SW 개발

[C] null point 코드가 동작하지 않는 이슈에 대해 (컴파일러 최적화옵션)

. . . 2020. 12. 18. 10:25
반응형

간혹, null point 를 체크하는 코드를 넣었으나 실제로 동작하지 않을때는 다음의 옵션을 살펴보자.

문제상황

코드상에서 null point 체크하는 코드를 넣었으나, 계속 코드가 진행되어 각종 에러가 발생하는경우가 발생한다.

    if (!tty)
        return;

즉, 위와같은 코드가 동작하지 않는다.

실제로 해당 이슈발생시, arm-none-linux-gnueabi-objdump -DSx 명령어를 통해서 디어셈해보면, null check 로 넣어놨던 코드가 없다.

해결

컴파일러의 최적화 옵션 -fdelete-null-pointer-checks 와 관련이 있다.

-fdelete-null-pointer-checks
  Assume that programs cannot safely dereference null pointers, and that no code or data element resides there. This enables simple constant folding optimizations at all optimization levels. In addition, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers; these assume that if a pointer is checked after it has already been dereferenced, it cannot be null.
  Note however that in some environments this assumption is not true. Use -fno-delete-null-pointer-checks to disable this optimization for programs that depend on that behavior.
  Some targets, especially embedded ones, disable this option at all levels. Otherwise it is enabled at all levels: -O0, -O1, -O2, -O3, -Os. Passes that use the information are enabled independently at different optimization levels.

즉, gcc 의 코드 최적화 옵션에 따라서 null point 를 체크하는 루틴이 최적화 되어버릴 수 있다는것이다. -fdelete-null-pointer-checks 해당부분을 추가하여 null point 관련 최적화를 강제로 하지 않게 한다.

컴파일러 옵션에 위의 내용을 넣고 디어셈해서 코드를 확인해보면 된다.

반응형