Wednesday 29 November 2017

c - casting void pointers






Possible
Duplicates:

href="https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc">Do I
cast the result of malloc?
href="https://stackoverflow.com/questions/953112/should-i-explicitly-cast-mallocs-return-value">Should
I explicitly cast malloc()'s return value?







Hello,



gcc
4.4.4 c89



Normally I don't cast the return
result from a malloc call.



int
*int_ptr = NULL;
int_ptr =
malloc(sizeof(int));



However,
I have read on here, that if you cast it can hide errors. How does it hide errors if you
explicitly cast to an int?



int_ptr
=
(int*)malloc(sizeof(int));


Also,
I was reading a c programming book that stated it was good programming practice to cast
from a void pointer including a call from
malloc.



Which would be good programming
practice?




int *int_ptr
= NULL;
void *ptr = NULL;

int_ptr =
ptr;


or



int_ptr
=
(int*)ptr;



Many
thanks for any advice,


itemprop="text">
class="normal">Answer





How does it
hide errors if you
explicitly cast to an
int?




It can hide
the error of neglecting to include stdlib.h before you call
malloc. Without the proper function declaration, the C compiler
can assume that it returns an int, and an explicit cast will
mask the fact that you're not calling malloc properly. See
Q7.6 and href="http://www.c-faq.com/malloc/sizetlong.html" rel="nofollow
noreferrer">Q7.16 from the comp.lang.c
FAQ.






Also, I was reading a c programming
book that stated it was
good
programming practice to cast from a
void pointer including a
call from
malloc.



Which would be
good programming

practice?





There
is no point to explicitly casting the result of malloc in C. It
potentially masks errors, and it increases the maintenance burden (if you ever decide to
change the allocated type, you now have an extra site in the code that must be
altered).



The only time you should perform an
explicit cast from void* so is if you will be compiling your
code as C++ since C++ does not allow that as an implicit cast. (But if you are writing
C++ code, you should be using static_cast in this
case.)


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...