'malloc 캐스팅'에 해당되는 글 1건

  1. 2014.05.29 malloc 를 캐스팅 하지 말자.
프로그래밍/C2014.05.29 11:22

출처: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc

In this question, someone suggested in a comment that I should not cast the results of malloci.e:

int *sieve = malloc(sizeof(int)*length);

rather than:

int *sieve = (int *)malloc(sizeof(int)*length);

Why would this be the case?


No; you don't cast the result, since:

  • It is unnecessary, as void * is automatically and safely promoted to any other pointer type in this case.
  • It can hide an error, if you forgot to include <stdlib.h>. This can cause crashes, in the worst case.
  • It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).
  • It makes you repeat yourself, which is generally bad.

As a clarification, note that I said "you don't cast", not "you don't need to cast". In my opinion, it's a failure to include the cast, even if you got it right. There are simply no benefits to doing it, but a bunch of potential risks, and including the cast indicates that you don't know about the risks.

Also note, as commentators point out, that the above changes for straight C, not C++. I very firmly believe in C and C++ as separate languages.

To add further, your code needlessly repeats the type information (int) which can cause errors. It's better to dereference the pointer being used to store the return value, to "lock" the two together:

int *sieve = malloc(length * sizeof *sieve);

This also moves the length to the front for increased visibility, and drops the redundant parentheses with sizeof; they are only needed when the argument is a type name. Many people seem to not know (or ignore) this, which makes their code more verbose. Remember: sizeof is not a function! :)


@sirgeorge - without the prototype/decl (in stdlib.h), a C compiler might/will assume that malloc returns an int. Then the compiler generates code for the call in question as if it is getting an int. Then, say, you are compiling for a platform where pointers and ints do not have the same size, and you cast the returning int into a pointer. Bad juju. And the compiler, upon seeing the casting, won't give you a warning in this case. But if you don't cast it, then the compiler will complain abou the int-to-ptr assignment (and you will be able to detect the missing include for stdlib.h) –  luis.espinal Mar 14 '12 at 19:28 

신고

'프로그래밍 > C' 카테고리의 다른 글

for 문 multiple 조건 & 처리  (0) 2014.06.05
strerror 사용법, perror 사용법  (0) 2014.06.02
malloc 를 캐스팅 하지 말자.  (0) 2014.05.29
strtok에 NULL을 전달하는 이유  (0) 2014.05.29
함수포인터 & typdef를 이용한 함수포인터  (0) 2014.05.07
ternary operator  (0) 2014.04.13
Posted by code cat

티스토리 툴바