malloc(0) 할당 문제

개발/프로그래밍2008. 7. 3. 20:52
728x90

리눅스에서 malloc(0) 했을 때 할당이 되었으나

AIX에서 할당이 되지 않았다.
 

CFAQ에 나와 있는 내용

Q 11.26 malloc(0)은 무엇을 의미하죠? 이 때 널 포인터가 리턴되는 것인가요, 아니면 0 바이트를 가리키는 포인터가 리턴되는 인가요?

Answer ANSI/ISO 표준은 둘 중 하나일 수 있다고 말하고 있습니다; 그 결과는 구현 방법에 의존적입니다.

 

 

malloc(0)

malloc(0) can either return a null pointer or a pointer to a 0 length region of memory. We can deal with this variation in one of (at least) 3 ways.

 

Ignore it.

             #define xnalloc(_t,_n)          ((_t*)malloc((_n)*sizeof(_t)))

Have a 0 length region always return 0.

             #define xnalloc(_t,_n)          \

                           ( ((_n)==0) ? ((_t*)0) : ((_t*)malloc((_n)*sizeof(_t))) )

Disallow it.

             #define xnalloc(_t,_n)          \

                           ( assert((_n) != 0 ), ((_t*)malloc((_n)*sizeof(_t))) )

My personal preference is to pick the third. Occasionally it is legitimate to allocate a 0 length object. In that case, we have to write:

             if( n == 0 ) {

               p = 0;

             }

             else {

               p = xnalloc(Type, n);

             }

However, fairly often when we are allocating a 0 length object it indicates the presence of a potential bug (n should never have been 0), or a performance optimization (if n is 0, then there is no work to be done, so don't execute the rest of the function).

참조 URL

728x90

작성자

Posted by 일퍼센트

관련 글

댓글 영역