C 언어 시큐어 코딩 - Preprocessor-3

함수 형태 매크로 호출 시 전처리 지시문을 사용하지 않는다.

매크로 인자 값에 #define, #ifdef, #include와 같은 전처리 지시문을 포함하지 않는다. 이 규칙은 매크로를 사용하여 함수가 구현되었는지 여부를 알 수 없는 함수에 대한 인수에서 전처리 지시문을 사용하는 경우에도 적용된다. 예를 들어, memcpy(), printf(), assert() 같은 표준 라이브러리 함수는 매크로로 구현 될 수 있다.

잘못된 코드 예제

예제(GCC Bug)에서 전처리 지시문을 사용하여 memcpy()에 대한 플랫폼 별 인수를 지정한다. 그러나 memcpy() 함수가 매크로를 사용하여 구현된 경우 코드는 정의되지 않은 동작을 유발한다.

#include <string.h>

void func(const char *src) {
  /* Validate the source string; calculate size */
  char *dest;
  /* malloc() destination string */
  memcpy(dest, src,
    #ifdef PLATFORM1
      12
    #else
      24
    #endif
  );
  /* ... */
}

올바른 코드 예제

예제에서 memcpy() 함수 호출 방법은 호출 외부에서 결정된다.

#include <string.h>

void func(const char *src) {
  /* Validate the source string; calculate size */
  char *dest;
  /* malloc() destination string */ 
  #ifdef PLATFORM1
    memcpy(dest, src, 12);
  #else
    memcpy(dest, src, 24);
  #endif
  /* ... */
}

results matching ""

    No results matching ""