Related
In this question, someone suggested in a comment that I should not cast the result of malloc. i.e., I should do this:
int *sieve = malloc(sizeof(*sieve) * length);
rather than:
int *sieve = (int *) malloc(sizeof(*sieve) * length);
Why would this be the case?
TL;DR
int *sieve = (int *) malloc(sizeof(int) * length);
has two problems. The cast and that you're using the type instead of variable as argument for sizeof. Instead, do like this:
int *sieve = malloc(sizeof *sieve * length);
Long version
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 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.
It can hide an error if you forgot to include <stdlib.h>. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you're hiding a warning by casting and might lose bits of your returned address. Note: as of C99 implicit functions are gone from C, and this point is no longer relevant since there's no automatic assumption that undeclared functions return int.
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 talks about 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 de-reference 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! :)
While moving length to the front may increase visibility in some rare cases, one should also pay attention that in the general case, it should be better to write the expression as:
int *sieve = malloc(sizeof *sieve * length);
Since keeping the sizeof first, in this case, ensures multiplication is done with at least size_t math.
Compare: malloc(sizeof *sieve * length * width) vs. malloc(length * width * sizeof *sieve) the second may overflow the length * width when width and length are smaller types than size_t.
In C, you don't need to cast the return value of malloc. The pointer to void returned by malloc is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed. A preferred alternative among the community is to use the following:
int *sieve = malloc(sizeof *sieve * length);
which additionally frees you from having to worry about changing the right-hand side of the expression if ever you change the type of sieve.
Casts are bad, as people have pointed out. Especially pointer casts.
You do cast, because:
It makes your code more portable between C and C++, and as SO experience shows, a great many programmers claim they are writing in C when they are really writing in C++ (or C plus local compiler extensions).
Failing to do so can hide an error: note all the SO examples of confusing when to write type * versus type **.
The idea that it keeps you from noticing you failed to #include an appropriate header file misses the forest for the trees. It's the same as saying "don't worry about the fact you failed to ask the compiler to complain about not seeing prototypes -- that pesky stdlib.h is the REAL important thing to remember!"
It forces an extra cognitive cross-check. It puts the (alleged) desired type right next to the arithmetic you're doing for the raw size of that variable. I bet you could do an SO study that shows that malloc() bugs are caught much faster when there's a cast. As with assertions, annotations that reveal intent decrease bugs.
Repeating yourself in a way that the machine can check is often a great idea. In fact, that's what an assertion is, and this use of cast is an assertion. Assertions are still the most general technique we have for getting code correct, since Turing came up with the idea so many years ago.
As others stated, it is not needed for C, but necessary for C++. If you think you are going to compile your C code with a C++ compiler, for whatever reasons, you can use a macro instead, like:
#ifdef __cplusplus
# define MALLOC(type) ((type *)malloc(sizeof(type)))
# define CALLOC(count, type) ((type *)calloc(count, sizeof(type)))
#else
# define MALLOC(type) (malloc(sizeof(type)))
# define CALLOC(count, type) (calloc(count, sizeof(type)))
#endif
# define FREE(pointer) free(pointer)
That way you can still write it in a very compact way:
int *sieve = MALLOC(int); // allocate single int => compare to stack int sieve = ???;
int *sieve_arr = CALLOC(4, int); // allocate 4 times size of int => compare to stack (int sieve_arr[4] = {0, 0, 0, 0};
// do something with the ptr or the value
FREE(sieve);
FREE(sieve_arr);
and it will compile for C and C++.
From the Wikipedia:
Advantages to casting
Including the cast may allow a C program or function to compile as C++.
The cast allows for pre-1989 versions of malloc that originally returned a char *.
Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call (although modern compilers and static analyzers can warn on such behaviour without requiring the cast).
Disadvantages to casting
Under the ANSI C standard, the cast is redundant.
Adding the cast may mask failure to include the header stdlib.h, in
which the prototype for malloc is found. In the absence of a
prototype for malloc, the standard requires that the C compiler
assume malloc returns an int. If there is no cast, a warning is
issued when this integer is assigned to the pointer; however, with
the cast, this warning is not produced, hiding a bug. On certain
architectures and data models (such as LP64 on 64-bit systems, where
long and pointers are 64-bit and int is 32-bit), this error can
actually result in undefined behaviour, as the implicitly declared
malloc returns a 32-bit value whereas the actually defined function
returns a 64-bit value. Depending on calling conventions and memory
layout, this may result in stack smashing. This issue is less likely
to go unnoticed in modern compilers, as they uniformly produce
warnings that an undeclared function has been used, so a warning will
still appear. For example, GCC's default behaviour is to show a
warning that reads "incompatible implicit declaration of built-in
function" regardless of whether the cast is present or not.
If the type of the pointer is changed at its declaration, one may
also, need to change all lines where malloc is called and cast.
Although malloc without casting is preferred method and most experienced programmers choose it, you should use whichever you like having aware of the issues.
i.e: If you need to compile C program as C++ (Although it is a separate language) you must cast the result of use malloc.
In C you can implicitly convert a void pointer to any other kind of pointer, so a cast is not necessary. Using one may suggest to the casual observer that there is some reason why one is needed, which may be misleading.
You don't cast the result of malloc, because doing so adds pointless clutter to your code.
The most common reason why people cast the result of malloc is because they are unsure about how the C language works. That's a warning sign: if you don't know how a particular language mechanism works, then don't take a guess. Look it up or ask on Stack Overflow.
Some comments:
A void pointer can be converted to/from any other pointer type without an explicit cast (C11 6.3.2.3 and 6.5.16.1).
C++ will however not allow an implicit cast between void* and another pointer type. So in C++, the cast would have been correct. But if you program in C++, you should use new and not malloc(). And you should never compile C code using a C++ compiler.
If you need to support both C and C++ with the same source code, use compiler switches to mark the differences. Do not attempt to sate both language standards with the same code, because they are not compatible.
If a C compiler cannot find a function because you forgot to include the header, you will get a compiler/linker error about that. So if you forgot to include <stdlib.h> that's no biggie, you won't be able to build your program.
On ancient compilers that follow a version of the standard which is more than 25 years old, forgetting to include <stdlib.h> would result in dangerous behavior. Because in that ancient standard, functions without a visible prototype implicitly converted the return type to int. Casting the result from malloc explicitly would then hide away this bug.
But that is really a non-issue. You aren't using a 25 years old computer, so why would you use a 25 years old compiler?
In C you get an implicit conversion from void * to any other (data) pointer.
Casting the value returned by malloc() is not necessary now, but I'd like to add one point that seems no one has pointed out:
In the ancient days, that is, before ANSI C provides the void * as the generic type of pointers, char * is the type for such usage. In that case, the cast can shut down the compiler warnings.
Reference: C FAQ
Just adding my experience, studying computer engineering I see that the two or three professors that I have seen writing in C always cast malloc, however the one I asked (with an immense CV and understanding of C) told me that it is absolutely unnecessary but only used to be absolutely specific, and to get the students into the mentality of being absolutely specific. Essentially casting will not change anything in how it works, it does exactly what it says, allocates memory, and casting does not effect it, you get the same memory, and even if you cast it to something else by mistake (and somehow evade compiler errors) C will access it the same way.
Edit: Casting has a certain point. When you use array notation, the code generated has to know how many memory places it has to advance to reach the beginning of the next element, this is achieved through casting. This way you know that for a double you go 8 bytes ahead while for an int you go 4, and so on. Thus it has no effect if you use pointer notation, in array notation it becomes necessary.
It is not mandatory to cast the results of malloc, since it returns void* , and a void* can be pointed to any datatype.
This is what The GNU C Library Reference manual says:
You can store the result of malloc into any pointer variable without a
cast, because ISO C automatically converts the type void * to another
type of pointer when necessary. But the cast is necessary in contexts
other than assignment operators or if you might want your code to run
in traditional C.
And indeed the ISO C11 standard (p347) says so:
The pointer returned if the allocation succeeds is suitably aligned so
that it may be assigned to a pointer to any type of object with a
fundamental alignment requirement and then used to access such an
object or an array of such objects in the space allocated (until the
space is explicitly deallocated)
A void pointer is a generic object pointer and C supports implicit conversion from a void pointer type to other types, so there is no need of explicitly typecasting it.
However, if you want the same code work perfectly compatible on a C++ platform, which does not support implicit conversion, you need to do the typecasting, so it all depends on usability.
The returned type is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
It depends on the programming language and compiler. If you use malloc in C, there is no need to type cast it, as it will automatically type cast. However, if you are using C++, then you should type cast because malloc will return a void* type.
In the C language, a void pointer can be assigned to any pointer, which is why you should not use a type cast. If you want "type safe" allocation, I can recommend the following macro functions, which I always use in my C projects:
#include <stdlib.h>
#define NEW_ARRAY(ptr, n) (ptr) = malloc((n) * sizeof *(ptr))
#define NEW(ptr) NEW_ARRAY((ptr), 1)
With these in place you can simply say
NEW_ARRAY(sieve, length);
For non-dynamic arrays, the third must-have function macro is
#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])
which makes array loops safer and more convenient:
int i, a[100];
for (i = 0; i < LEN(a); i++) {
...
}
People used to GCC and Clang are spoiled. It's not all that good out there.
I have been pretty horrified over the years by the staggeringly aged compilers I've been required to use. Often companies and managers adopt an ultra-conservative approach to changing compilers and will not even test if a new compiler ( with better standards compliance and code optimization ) will work in their system. The practical reality for working developers is that when you're coding you need to cover your bases and, unfortunately, casting mallocs is a good habit if you cannot control what compiler may be applied to your code.
I would also suggest that many organizations apply a coding standard of their own and that that should be the method people follow if it is defined. In the absence of explicit guidance I tend to go for most likely to compile everywhere, rather than slavish adherence to a standard.
The argument that it's not necessary under current standards is quite valid. But that argument omits the practicalities of the real world. We do not code in a world ruled exclusively by the standard of the day, but by the practicalities of what I like to call "local management's reality field". And that's bent and twisted more than space time ever was. :-)
YMMV.
I tend to think of casting malloc as a defensive operation. Not pretty, not perfect, but generally safe. ( Honestly, if you've not included stdlib.h then you've way more problems than casting malloc ! ).
This question is subject of opinion-based abuse.
Sometimes I notice comments like that:
Don't cast the result of malloc
or
Why you don't cast the result of malloc
on questions where OP uses casting. The comments itself contain a hyperlink to this question.
That is in any possible manner inappropriate and incorrect as well. There is no right and no wrong when it is truly a matter of one's own coding-style.
Why is this happening?
It's based upon two reasons:
This question is indeed opinion-based. Technically, the question should have been closed as opinion-based years ago. A "Do I" or "Don't I" or equivalent "Should I" or "Shouldn't I" question, you just can't answer focused without an attitude of one's own opinion. One of the reason to close a question is because it "might lead to opinion-based answers" as it is well shown here.
Many answers (including the most apparent and accepted answer of #unwind) are either completely or almost entirely opinion-based (f.e. a mysterious "clutter" that would be added to your code if you do casting or repeating yourself would be bad) and show a clear and focused tendency to omit the cast. They argue about the redundancy of the cast on one side but also and even worse argue to solve a bug caused by a bug/failure of programming itself - to not #include <stdlib.h> if one want to use malloc().
I want to bring a true view of some points discussed, with less of my personal opinion. A few points need to be noted especially:
Such a very susceptible question to fall into one's own opinion needs an answer with neutral pros and cons. Not only cons or pros.
A good overview of pros and cons is listed in this answer:
https://stackoverflow.com/a/33047365/12139179
(I personally consider this because of that reason the best answer, so far.)
One reason which is encountered at most to reason the omission of the cast is that the cast might hide a bug.
If someone uses an implicit declared malloc() that returns int (implicit functions are gone from the standard since C99) and sizeof(int) != sizeof(int*), as shown in this question
Why does this code segfault on 64-bit architecture but work fine on 32-bit?
the cast would hide a bug.
While this is true, it only shows half of the story as the omission of the cast would only be a forward-bringing solution to an even bigger bug - not including stdlib.h when using malloc().
This will never be a serious issue, If you,
Use a compiler compliant to C99 or above (which is recommended and should be mandatory), and
Aren't so absent to forgot to include stdlib.h, when you want to use malloc() in your code, which is a huge bug itself.
Some people argue about C++ compliance of C code, as the cast is obliged in C++.
First of all to say in general: Compiling C code with a C++ compiler is not a good practice.
C and C++ are in fact two completely different languages with different semantics.
But If you really want/need to make C code compliant to C++ and vice versa use compiler switches instead of any cast.
Since the cast is with tendency declared as redundant or even harmful, I want to take a focus on these questions, which give good reasons why casting can be useful or even necessary:
https://stackoverflow.com/a/34094068/12139179
https://stackoverflow.com/a/36297486/12139179
https://stackoverflow.com/a/33044300/12139179
The cast can be non-beneficial when your code, respectively the type of the assigned pointer (and with that the type of the cast), changes, although this is in most cases unlikely. Then you would need to maintain/change all casts too and if you have a few thousand calls to memory-management functions in your code, this can really summarizing up and decrease the maintenance efficiency.
Summary:
Fact is, that the cast is redundant per the C standard (already since ANSI-C (C89/C90)) if the assigned pointer point to an object of fundamental alignment requirement (which includes the most of all objects).
You don't need to do the cast as the pointer is automatically aligned in this case:
"The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated)."
Source: C18, §7.22.3/1
"A fundamental alignment is a valid alignment less than or equal to _Alignof (max_align_t). Fundamental alignments shall be supported by the implementation for objects of all storage durations. The alignment requirements of the following types shall be fundamental alignments:
— all atomic, qualified, or unqualified basic types;
— all atomic, qualified, or unqualified enumerated types;
— all atomic, qualified, or unqualified pointer types;
— all array types whose element type has a fundamental alignment requirement;57)
— all types specified in Clause 7 as complete object types;
— all structure or union types all of whose elements have types with fundamental alignment requirements and none of whose elements have an alignment specifier specifying an alignment that is not a fundamental alignment.
As specified in 6.2.1, the later declaration might hide the prior declaration."
Source: C18, §6.2.8/2
However, if you allocate memory for an implementation-defined object of extended alignment requirement, the cast would be needed.
An extended alignment is represented by an alignment greater than _Alignof (max_align_t). It is implementation-defined whether any extended alignments are supported and the storage durations for which they are supported. A type having an extended alignment requirement is an over-aligned type.58)
Source. C18, §6.2.8/3
Everything else is a matter of the specific use case and one's own opinion.
Please be careful how you educate yourself.
I recommend you to read all of the answers made so far carefully first (as well as their comments which may point at a failure) and then build your own opinion if you or if you not cast the result of malloc() at a specific case.
Please note:
There is no right and wrong answer to that question. It is a matter of style and you yourself decide which way you choose (if you aren't forced to by education or job of course). Please be aware of that and don't let trick you.
Last note: I voted to lately close this question as opinion-based, which is indeed needed since years. If you got the close/reopen privilege I would like to invite you to do so, too.
No, you don't cast the result of malloc().
In general, you don't cast to or from void *.
A typical reason given for not doing so is that failure to #include <stdlib.h> could go unnoticed. This isn't an issue anymore for a long time now as C99 made implicit function declarations illegal, so if your compiler conforms to at least C99, you will get a diagnostic message.
But there's a much stronger reason not to introduce unnecessary pointer casts:
In C, a pointer cast is almost always an error. This is because of the following rule (§6.5 p7 in N1570, the latest draft for C11):
An object shall have its stored value accessed only by an lvalue expression that has one of
the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the
object,
— a type that is the signed or unsigned type corresponding to a qualified version of the
effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its
members (including, recursively, a member of a subaggregate or contained union), or
— a character type.
This is also known as the strict aliasing rule. So the following code is undefined behavior:
long x = 5;
double *p = (double *)&x;
double y = *p;
And, sometimes surprisingly, the following is as well:
struct foo { int x; };
struct bar { int x; int y; };
struct bar b = { 1, 2};
struct foo *p = (struct foo *)&b;
int z = p->x;
Sometimes, you do need to cast pointers, but given the strict aliasing rule, you have to be very careful with it. So, any occurrence of a pointer cast in your code is a place you have to double-check for its validity. Therefore, you never write an unnecessary pointer cast.
tl;dr
In a nutshell: Because in C, any occurrence of a pointer cast should raise a red flag for code requiring special attention, you should never write unnecessary pointer casts.
Side notes:
There are cases where you actually need a cast to void *, e.g. if you want to print a pointer:
int x = 5;
printf("%p\n", (void *)&x);
The cast is necessary here, because printf() is a variadic function, so implicit conversions don't work.
In C++, the situation is different. Casting pointer types is somewhat common (and correct) when dealing with objects of derived classes. Therefore, it makes sense that in C++, the conversion to and from void * is not implicit. C++ has a whole set of different flavors of casting.
I put in the cast simply to show disapproval of the ugly hole in the type system, which allows code such as the following snippet to compile without diagnostics, even though no casts are used to bring about the bad conversion:
double d;
void *p = &d;
int *q = p;
I wish that didn't exist (and it doesn't in C++) and so I cast. It represents my taste, and my programming politics. I'm not only casting a pointer, but effectively, casting a ballot, and casting out demons of stupidity. If I can't actually cast out stupidity, then at least let me express the wish to do so with a gesture of protest.
In fact, a good practice is to wrap malloc (and friends) with functions that return unsigned char *, and basically never to use void * in your code. If you need a generic pointer-to-any-object, use a char * or unsigned char *, and have casts in both directions. The one relaxation that can be indulged, perhaps, is using functions like memset and memcpy without casts.
On the topic of casting and C++ compatibility, if you write your code so that it compiles as both C and C++ (in which case you have to cast the return value of malloc when assigning it to something other than void *), you can do a very helpful thing for yourself: you can use macros for casting which translate to C++ style casts when compiling as C++, but reduce to a C cast when compiling as C:
/* In a header somewhere */
#ifdef __cplusplus
#define strip_qual(TYPE, EXPR) (const_cast<TYPE>(EXPR))
#define convert(TYPE, EXPR) (static_cast<TYPE>(EXPR))
#define coerce(TYPE, EXPR) (reinterpret_cast<TYPE>(EXPR))
#else
#define strip_qual(TYPE, EXPR) ((TYPE) (EXPR))
#define convert(TYPE, EXPR) ((TYPE) (EXPR))
#define coerce(TYPE, EXPR) ((TYPE) (EXPR))
#endif
If you adhere to these macros, then a simple grep search of your code base for these identifiers will show you where all your casts are, so you can review whether any of them are incorrect.
Then, going forward, if you regularly compile the code with C++, it will enforce the use of an appropriate cast. For instance, if you use strip_qual just to remove a const or volatile, but the program changes in such a way that a type conversion is now involved, you will get a diagnostic, and you will have to use a combination of casts to get the desired conversion.
To help you adhere to these macros, the the GNU C++ (not C!) compiler has a beautiful feature: an optional diagnostic which is produced for all occurrences of C style casts.
-Wold-style-cast (C++ and Objective-C++ only)
Warn if an old-style (C-style) cast to a non-void type is used
within a C++ program. The new-style casts (dynamic_cast,
static_cast, reinterpret_cast, and const_cast) are less vulnerable
to unintended effects and much easier to search for.
If your C code compiles as C++, you can use this -Wold-style-cast option to find out all occurrences of the (type) casting syntax that may creep into the code, and follow up on these diagnostics by replacing it with an appropriate choice from among the above macros (or a combination, if necessary).
This treatment of conversions is the single largest standalone technical justification for working in a "Clean C": the combined C and C++ dialect, which in turn technically justifies casting the return value of malloc.
The best thing to do when programming in C whenever it is possible:
Make your program compile through a C compiler with all warnings turned on -Wall and fix all errors and warnings
Make sure there are no variables declared as auto
Then compile it using a C++ compiler with -Wall and -std=c++11. Fix all errors and warnings.
Now compile using the C compiler again. Your program should now compile without any warning and contain fewer bugs.
This procedure lets you take advantage of C++ strict type checking, thus reducing the number of bugs. In particular, this procedure forces you to include stdlib.hor you will get
malloc was not declared within this scope
and also forces you to cast the result of malloc or you will get
invalid conversion from void* to T*
or what ever your target type is.
The only benefits from writing in C instead of C++ I can find are
C has a well specified ABI
C++ may generate more code [exceptions, RTTI, templates, runtime polymorphism]
Notice that the second cons should in the ideal case disappear when using the subset common to C together with the static polymorphic feature.
For those that finds C++ strict rules inconvenient, we can use the C++11 feature with inferred type
auto memblock=static_cast<T*>(malloc(n*sizeof(T))); //Mult may overflow...
I prefer to do the cast, but not manually. My favorite is using g_new and g_new0 macros from glib. If glib is not used, I would add similar macros. Those macros reduce code duplication without compromising type safety. If you get the type wrong, you would get an implicit cast between non-void pointers, which would cause a warning (error in C++). If you forget to include the header that defines g_new and g_new0, you would get an error. g_new and g_new0 both take the same arguments, unlike malloc that takes fewer arguments than calloc. Just add 0 to get zero-initialized memory. The code can be compiled with a C++ compiler without changes.
Casting is only for C++ not C.In case you are using a C++ compiler you better change it to C compiler.
The casting of malloc is unnecessary in C but mandatory in C++.
Casting is unnecessary in C because of:
void * is automatically and safely promoted to any other pointer type in the case of C.
It can hide an error if you forgot to include <stdlib.h>. This can cause crashes.
If pointers and integers are differently sized, then you're hiding a warning by casting and might lose bits of your returned address.
If the type of the pointer is changed at its declaration, one may also need to change all lines where malloc is called and cast.
On the other hand, casting may increase the portability of your program. i.e, it allows a C program or function to compile as C++.
The concept behind void pointer is that it can be casted to any data type that is why malloc returns void. Also you must be aware of automatic typecasting. So it is not mandatory to cast the pointer though you must do it. It helps in keeping the code clean and helps debugging
A void pointer is a generic pointer and C supports implicit conversion from a void pointer type to other types, so there is no need of explicitly typecasting it.
However, if you want the same code work perfectly compatible on a C++ platform, which does not support implicit conversion, you need to do the typecasting, so it all depends on usability.
As other stated, it is not needed for C, but for C++.
Including the cast may allow a C program or function to compile as C++.
In C it is unnecessary, as void * is automatically and safely promoted to any other pointer type.
But if you cast then, it can hide an error if you forgot to include
stdlib.h. This can cause crashes (or, worse, not cause a crash
until way later in some totally different part of the code).
Because stdlib.h contains the prototype for malloc is found. In the
absence of a prototype for malloc, the standard requires that the C
compiler assumes malloc returns an int. If there is no cast, a
warning is issued when this integer is assigned to the pointer;
however, with the cast, this warning is not produced, hiding a bug.
The main issue with malloc is to get the right size.
The memory returned form malloc() is untyped, and it will not magically gain an effective type due to a simple cast.
I guess that both approaches are fine and the choice should depend on programmer intention.
If allocating memory for a type, then use a cast.
ptr = (T*)malloc(sizeof(T));
If allocating memory for a given pointer, then don't use a cast.
ptr = malloc(sizeof *ptr);
Ad 1
The first method assures the correct size by allocating memory for a given type, and then casting it to assure that it is assigned to the right pointer. If incorrect type of ptr is used then the compiler will issue a warning/error. If the type of ptr is changed, then the compiler will point the places where the code needs refactoring.
Moreover, the first method can be combined into a macro similar to new operator in C++.
#define NEW(T) ((T*)malloc(sizeof(T)))
...
ptr = NEW(T);
Moreover this method works if ptr is void*.
Ad 2
The second methods does not care about the types, it assures the correct size by taking it from the pointer's type. The main advantage of this method is the automatic adjustment of storage size whenever the type of ptr is changed.
It can save some time (or errors) when refactoring.
The disadvantage is that the method does not work if ptr is void* but it may be perceived as a good thing. And that it does not work with C++ so it should not be used in inlined functions in headers that are going to be used by C++ programs.
Personally, I prefer the second option.
For me, the take home and conclusion here is that casting malloc in C is totally NOT necessary but if you however cast, it wont affect malloc as malloc will still allocate to you your requested blessed memory space.
Another take home is the reason or one of the reasons people do casting and this is to enable them compile same program either in C or C++.
There may be other reasons but other reasons, almost certainly, would land you in serious trouble sooner or later.
In this question, someone suggested in a comment that I should not cast the result of malloc. i.e., I should do this:
int *sieve = malloc(sizeof(*sieve) * length);
rather than:
int *sieve = (int *) malloc(sizeof(*sieve) * length);
Why would this be the case?
TL;DR
int *sieve = (int *) malloc(sizeof(int) * length);
has two problems. The cast and that you're using the type instead of variable as argument for sizeof. Instead, do like this:
int *sieve = malloc(sizeof *sieve * length);
Long version
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 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.
It can hide an error if you forgot to include <stdlib.h>. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you're hiding a warning by casting and might lose bits of your returned address. Note: as of C99 implicit functions are gone from C, and this point is no longer relevant since there's no automatic assumption that undeclared functions return int.
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 talks about 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 de-reference 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! :)
While moving length to the front may increase visibility in some rare cases, one should also pay attention that in the general case, it should be better to write the expression as:
int *sieve = malloc(sizeof *sieve * length);
Since keeping the sizeof first, in this case, ensures multiplication is done with at least size_t math.
Compare: malloc(sizeof *sieve * length * width) vs. malloc(length * width * sizeof *sieve) the second may overflow the length * width when width and length are smaller types than size_t.
In C, you don't need to cast the return value of malloc. The pointer to void returned by malloc is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed. A preferred alternative among the community is to use the following:
int *sieve = malloc(sizeof *sieve * length);
which additionally frees you from having to worry about changing the right-hand side of the expression if ever you change the type of sieve.
Casts are bad, as people have pointed out. Especially pointer casts.
You do cast, because:
It makes your code more portable between C and C++, and as SO experience shows, a great many programmers claim they are writing in C when they are really writing in C++ (or C plus local compiler extensions).
Failing to do so can hide an error: note all the SO examples of confusing when to write type * versus type **.
The idea that it keeps you from noticing you failed to #include an appropriate header file misses the forest for the trees. It's the same as saying "don't worry about the fact you failed to ask the compiler to complain about not seeing prototypes -- that pesky stdlib.h is the REAL important thing to remember!"
It forces an extra cognitive cross-check. It puts the (alleged) desired type right next to the arithmetic you're doing for the raw size of that variable. I bet you could do an SO study that shows that malloc() bugs are caught much faster when there's a cast. As with assertions, annotations that reveal intent decrease bugs.
Repeating yourself in a way that the machine can check is often a great idea. In fact, that's what an assertion is, and this use of cast is an assertion. Assertions are still the most general technique we have for getting code correct, since Turing came up with the idea so many years ago.
As others stated, it is not needed for C, but necessary for C++. If you think you are going to compile your C code with a C++ compiler, for whatever reasons, you can use a macro instead, like:
#ifdef __cplusplus
# define MALLOC(type) ((type *)malloc(sizeof(type)))
# define CALLOC(count, type) ((type *)calloc(count, sizeof(type)))
#else
# define MALLOC(type) (malloc(sizeof(type)))
# define CALLOC(count, type) (calloc(count, sizeof(type)))
#endif
# define FREE(pointer) free(pointer)
That way you can still write it in a very compact way:
int *sieve = MALLOC(int); // allocate single int => compare to stack int sieve = ???;
int *sieve_arr = CALLOC(4, int); // allocate 4 times size of int => compare to stack (int sieve_arr[4] = {0, 0, 0, 0};
// do something with the ptr or the value
FREE(sieve);
FREE(sieve_arr);
and it will compile for C and C++.
From the Wikipedia:
Advantages to casting
Including the cast may allow a C program or function to compile as C++.
The cast allows for pre-1989 versions of malloc that originally returned a char *.
Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call (although modern compilers and static analyzers can warn on such behaviour without requiring the cast).
Disadvantages to casting
Under the ANSI C standard, the cast is redundant.
Adding the cast may mask failure to include the header stdlib.h, in
which the prototype for malloc is found. In the absence of a
prototype for malloc, the standard requires that the C compiler
assume malloc returns an int. If there is no cast, a warning is
issued when this integer is assigned to the pointer; however, with
the cast, this warning is not produced, hiding a bug. On certain
architectures and data models (such as LP64 on 64-bit systems, where
long and pointers are 64-bit and int is 32-bit), this error can
actually result in undefined behaviour, as the implicitly declared
malloc returns a 32-bit value whereas the actually defined function
returns a 64-bit value. Depending on calling conventions and memory
layout, this may result in stack smashing. This issue is less likely
to go unnoticed in modern compilers, as they uniformly produce
warnings that an undeclared function has been used, so a warning will
still appear. For example, GCC's default behaviour is to show a
warning that reads "incompatible implicit declaration of built-in
function" regardless of whether the cast is present or not.
If the type of the pointer is changed at its declaration, one may
also, need to change all lines where malloc is called and cast.
Although malloc without casting is preferred method and most experienced programmers choose it, you should use whichever you like having aware of the issues.
i.e: If you need to compile C program as C++ (Although it is a separate language) you must cast the result of use malloc.
In C you can implicitly convert a void pointer to any other kind of pointer, so a cast is not necessary. Using one may suggest to the casual observer that there is some reason why one is needed, which may be misleading.
You don't cast the result of malloc, because doing so adds pointless clutter to your code.
The most common reason why people cast the result of malloc is because they are unsure about how the C language works. That's a warning sign: if you don't know how a particular language mechanism works, then don't take a guess. Look it up or ask on Stack Overflow.
Some comments:
A void pointer can be converted to/from any other pointer type without an explicit cast (C11 6.3.2.3 and 6.5.16.1).
C++ will however not allow an implicit cast between void* and another pointer type. So in C++, the cast would have been correct. But if you program in C++, you should use new and not malloc(). And you should never compile C code using a C++ compiler.
If you need to support both C and C++ with the same source code, use compiler switches to mark the differences. Do not attempt to sate both language standards with the same code, because they are not compatible.
If a C compiler cannot find a function because you forgot to include the header, you will get a compiler/linker error about that. So if you forgot to include <stdlib.h> that's no biggie, you won't be able to build your program.
On ancient compilers that follow a version of the standard which is more than 25 years old, forgetting to include <stdlib.h> would result in dangerous behavior. Because in that ancient standard, functions without a visible prototype implicitly converted the return type to int. Casting the result from malloc explicitly would then hide away this bug.
But that is really a non-issue. You aren't using a 25 years old computer, so why would you use a 25 years old compiler?
In C you get an implicit conversion from void * to any other (data) pointer.
Casting the value returned by malloc() is not necessary now, but I'd like to add one point that seems no one has pointed out:
In the ancient days, that is, before ANSI C provides the void * as the generic type of pointers, char * is the type for such usage. In that case, the cast can shut down the compiler warnings.
Reference: C FAQ
Just adding my experience, studying computer engineering I see that the two or three professors that I have seen writing in C always cast malloc, however the one I asked (with an immense CV and understanding of C) told me that it is absolutely unnecessary but only used to be absolutely specific, and to get the students into the mentality of being absolutely specific. Essentially casting will not change anything in how it works, it does exactly what it says, allocates memory, and casting does not effect it, you get the same memory, and even if you cast it to something else by mistake (and somehow evade compiler errors) C will access it the same way.
Edit: Casting has a certain point. When you use array notation, the code generated has to know how many memory places it has to advance to reach the beginning of the next element, this is achieved through casting. This way you know that for a double you go 8 bytes ahead while for an int you go 4, and so on. Thus it has no effect if you use pointer notation, in array notation it becomes necessary.
It is not mandatory to cast the results of malloc, since it returns void* , and a void* can be pointed to any datatype.
This is what The GNU C Library Reference manual says:
You can store the result of malloc into any pointer variable without a
cast, because ISO C automatically converts the type void * to another
type of pointer when necessary. But the cast is necessary in contexts
other than assignment operators or if you might want your code to run
in traditional C.
And indeed the ISO C11 standard (p347) says so:
The pointer returned if the allocation succeeds is suitably aligned so
that it may be assigned to a pointer to any type of object with a
fundamental alignment requirement and then used to access such an
object or an array of such objects in the space allocated (until the
space is explicitly deallocated)
A void pointer is a generic object pointer and C supports implicit conversion from a void pointer type to other types, so there is no need of explicitly typecasting it.
However, if you want the same code work perfectly compatible on a C++ platform, which does not support implicit conversion, you need to do the typecasting, so it all depends on usability.
The returned type is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
It depends on the programming language and compiler. If you use malloc in C, there is no need to type cast it, as it will automatically type cast. However, if you are using C++, then you should type cast because malloc will return a void* type.
In the C language, a void pointer can be assigned to any pointer, which is why you should not use a type cast. If you want "type safe" allocation, I can recommend the following macro functions, which I always use in my C projects:
#include <stdlib.h>
#define NEW_ARRAY(ptr, n) (ptr) = malloc((n) * sizeof *(ptr))
#define NEW(ptr) NEW_ARRAY((ptr), 1)
With these in place you can simply say
NEW_ARRAY(sieve, length);
For non-dynamic arrays, the third must-have function macro is
#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])
which makes array loops safer and more convenient:
int i, a[100];
for (i = 0; i < LEN(a); i++) {
...
}
People used to GCC and Clang are spoiled. It's not all that good out there.
I have been pretty horrified over the years by the staggeringly aged compilers I've been required to use. Often companies and managers adopt an ultra-conservative approach to changing compilers and will not even test if a new compiler ( with better standards compliance and code optimization ) will work in their system. The practical reality for working developers is that when you're coding you need to cover your bases and, unfortunately, casting mallocs is a good habit if you cannot control what compiler may be applied to your code.
I would also suggest that many organizations apply a coding standard of their own and that that should be the method people follow if it is defined. In the absence of explicit guidance I tend to go for most likely to compile everywhere, rather than slavish adherence to a standard.
The argument that it's not necessary under current standards is quite valid. But that argument omits the practicalities of the real world. We do not code in a world ruled exclusively by the standard of the day, but by the practicalities of what I like to call "local management's reality field". And that's bent and twisted more than space time ever was. :-)
YMMV.
I tend to think of casting malloc as a defensive operation. Not pretty, not perfect, but generally safe. ( Honestly, if you've not included stdlib.h then you've way more problems than casting malloc ! ).
This question is subject of opinion-based abuse.
Sometimes I notice comments like that:
Don't cast the result of malloc
or
Why you don't cast the result of malloc
on questions where OP uses casting. The comments itself contain a hyperlink to this question.
That is in any possible manner inappropriate and incorrect as well. There is no right and no wrong when it is truly a matter of one's own coding-style.
Why is this happening?
It's based upon two reasons:
This question is indeed opinion-based. Technically, the question should have been closed as opinion-based years ago. A "Do I" or "Don't I" or equivalent "Should I" or "Shouldn't I" question, you just can't answer focused without an attitude of one's own opinion. One of the reason to close a question is because it "might lead to opinion-based answers" as it is well shown here.
Many answers (including the most apparent and accepted answer of #unwind) are either completely or almost entirely opinion-based (f.e. a mysterious "clutter" that would be added to your code if you do casting or repeating yourself would be bad) and show a clear and focused tendency to omit the cast. They argue about the redundancy of the cast on one side but also and even worse argue to solve a bug caused by a bug/failure of programming itself - to not #include <stdlib.h> if one want to use malloc().
I want to bring a true view of some points discussed, with less of my personal opinion. A few points need to be noted especially:
Such a very susceptible question to fall into one's own opinion needs an answer with neutral pros and cons. Not only cons or pros.
A good overview of pros and cons is listed in this answer:
https://stackoverflow.com/a/33047365/12139179
(I personally consider this because of that reason the best answer, so far.)
One reason which is encountered at most to reason the omission of the cast is that the cast might hide a bug.
If someone uses an implicit declared malloc() that returns int (implicit functions are gone from the standard since C99) and sizeof(int) != sizeof(int*), as shown in this question
Why does this code segfault on 64-bit architecture but work fine on 32-bit?
the cast would hide a bug.
While this is true, it only shows half of the story as the omission of the cast would only be a forward-bringing solution to an even bigger bug - not including stdlib.h when using malloc().
This will never be a serious issue, If you,
Use a compiler compliant to C99 or above (which is recommended and should be mandatory), and
Aren't so absent to forgot to include stdlib.h, when you want to use malloc() in your code, which is a huge bug itself.
Some people argue about C++ compliance of C code, as the cast is obliged in C++.
First of all to say in general: Compiling C code with a C++ compiler is not a good practice.
C and C++ are in fact two completely different languages with different semantics.
But If you really want/need to make C code compliant to C++ and vice versa use compiler switches instead of any cast.
Since the cast is with tendency declared as redundant or even harmful, I want to take a focus on these questions, which give good reasons why casting can be useful or even necessary:
https://stackoverflow.com/a/34094068/12139179
https://stackoverflow.com/a/36297486/12139179
https://stackoverflow.com/a/33044300/12139179
The cast can be non-beneficial when your code, respectively the type of the assigned pointer (and with that the type of the cast), changes, although this is in most cases unlikely. Then you would need to maintain/change all casts too and if you have a few thousand calls to memory-management functions in your code, this can really summarizing up and decrease the maintenance efficiency.
Summary:
Fact is, that the cast is redundant per the C standard (already since ANSI-C (C89/C90)) if the assigned pointer point to an object of fundamental alignment requirement (which includes the most of all objects).
You don't need to do the cast as the pointer is automatically aligned in this case:
"The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated)."
Source: C18, §7.22.3/1
"A fundamental alignment is a valid alignment less than or equal to _Alignof (max_align_t). Fundamental alignments shall be supported by the implementation for objects of all storage durations. The alignment requirements of the following types shall be fundamental alignments:
— all atomic, qualified, or unqualified basic types;
— all atomic, qualified, or unqualified enumerated types;
— all atomic, qualified, or unqualified pointer types;
— all array types whose element type has a fundamental alignment requirement;57)
— all types specified in Clause 7 as complete object types;
— all structure or union types all of whose elements have types with fundamental alignment requirements and none of whose elements have an alignment specifier specifying an alignment that is not a fundamental alignment.
As specified in 6.2.1, the later declaration might hide the prior declaration."
Source: C18, §6.2.8/2
However, if you allocate memory for an implementation-defined object of extended alignment requirement, the cast would be needed.
An extended alignment is represented by an alignment greater than _Alignof (max_align_t). It is implementation-defined whether any extended alignments are supported and the storage durations for which they are supported. A type having an extended alignment requirement is an over-aligned type.58)
Source. C18, §6.2.8/3
Everything else is a matter of the specific use case and one's own opinion.
Please be careful how you educate yourself.
I recommend you to read all of the answers made so far carefully first (as well as their comments which may point at a failure) and then build your own opinion if you or if you not cast the result of malloc() at a specific case.
Please note:
There is no right and wrong answer to that question. It is a matter of style and you yourself decide which way you choose (if you aren't forced to by education or job of course). Please be aware of that and don't let trick you.
Last note: I voted to lately close this question as opinion-based, which is indeed needed since years. If you got the close/reopen privilege I would like to invite you to do so, too.
No, you don't cast the result of malloc().
In general, you don't cast to or from void *.
A typical reason given for not doing so is that failure to #include <stdlib.h> could go unnoticed. This isn't an issue anymore for a long time now as C99 made implicit function declarations illegal, so if your compiler conforms to at least C99, you will get a diagnostic message.
But there's a much stronger reason not to introduce unnecessary pointer casts:
In C, a pointer cast is almost always an error. This is because of the following rule (§6.5 p7 in N1570, the latest draft for C11):
An object shall have its stored value accessed only by an lvalue expression that has one of
the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the
object,
— a type that is the signed or unsigned type corresponding to a qualified version of the
effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its
members (including, recursively, a member of a subaggregate or contained union), or
— a character type.
This is also known as the strict aliasing rule. So the following code is undefined behavior:
long x = 5;
double *p = (double *)&x;
double y = *p;
And, sometimes surprisingly, the following is as well:
struct foo { int x; };
struct bar { int x; int y; };
struct bar b = { 1, 2};
struct foo *p = (struct foo *)&b;
int z = p->x;
Sometimes, you do need to cast pointers, but given the strict aliasing rule, you have to be very careful with it. So, any occurrence of a pointer cast in your code is a place you have to double-check for its validity. Therefore, you never write an unnecessary pointer cast.
tl;dr
In a nutshell: Because in C, any occurrence of a pointer cast should raise a red flag for code requiring special attention, you should never write unnecessary pointer casts.
Side notes:
There are cases where you actually need a cast to void *, e.g. if you want to print a pointer:
int x = 5;
printf("%p\n", (void *)&x);
The cast is necessary here, because printf() is a variadic function, so implicit conversions don't work.
In C++, the situation is different. Casting pointer types is somewhat common (and correct) when dealing with objects of derived classes. Therefore, it makes sense that in C++, the conversion to and from void * is not implicit. C++ has a whole set of different flavors of casting.
I put in the cast simply to show disapproval of the ugly hole in the type system, which allows code such as the following snippet to compile without diagnostics, even though no casts are used to bring about the bad conversion:
double d;
void *p = &d;
int *q = p;
I wish that didn't exist (and it doesn't in C++) and so I cast. It represents my taste, and my programming politics. I'm not only casting a pointer, but effectively, casting a ballot, and casting out demons of stupidity. If I can't actually cast out stupidity, then at least let me express the wish to do so with a gesture of protest.
In fact, a good practice is to wrap malloc (and friends) with functions that return unsigned char *, and basically never to use void * in your code. If you need a generic pointer-to-any-object, use a char * or unsigned char *, and have casts in both directions. The one relaxation that can be indulged, perhaps, is using functions like memset and memcpy without casts.
On the topic of casting and C++ compatibility, if you write your code so that it compiles as both C and C++ (in which case you have to cast the return value of malloc when assigning it to something other than void *), you can do a very helpful thing for yourself: you can use macros for casting which translate to C++ style casts when compiling as C++, but reduce to a C cast when compiling as C:
/* In a header somewhere */
#ifdef __cplusplus
#define strip_qual(TYPE, EXPR) (const_cast<TYPE>(EXPR))
#define convert(TYPE, EXPR) (static_cast<TYPE>(EXPR))
#define coerce(TYPE, EXPR) (reinterpret_cast<TYPE>(EXPR))
#else
#define strip_qual(TYPE, EXPR) ((TYPE) (EXPR))
#define convert(TYPE, EXPR) ((TYPE) (EXPR))
#define coerce(TYPE, EXPR) ((TYPE) (EXPR))
#endif
If you adhere to these macros, then a simple grep search of your code base for these identifiers will show you where all your casts are, so you can review whether any of them are incorrect.
Then, going forward, if you regularly compile the code with C++, it will enforce the use of an appropriate cast. For instance, if you use strip_qual just to remove a const or volatile, but the program changes in such a way that a type conversion is now involved, you will get a diagnostic, and you will have to use a combination of casts to get the desired conversion.
To help you adhere to these macros, the the GNU C++ (not C!) compiler has a beautiful feature: an optional diagnostic which is produced for all occurrences of C style casts.
-Wold-style-cast (C++ and Objective-C++ only)
Warn if an old-style (C-style) cast to a non-void type is used
within a C++ program. The new-style casts (dynamic_cast,
static_cast, reinterpret_cast, and const_cast) are less vulnerable
to unintended effects and much easier to search for.
If your C code compiles as C++, you can use this -Wold-style-cast option to find out all occurrences of the (type) casting syntax that may creep into the code, and follow up on these diagnostics by replacing it with an appropriate choice from among the above macros (or a combination, if necessary).
This treatment of conversions is the single largest standalone technical justification for working in a "Clean C": the combined C and C++ dialect, which in turn technically justifies casting the return value of malloc.
The best thing to do when programming in C whenever it is possible:
Make your program compile through a C compiler with all warnings turned on -Wall and fix all errors and warnings
Make sure there are no variables declared as auto
Then compile it using a C++ compiler with -Wall and -std=c++11. Fix all errors and warnings.
Now compile using the C compiler again. Your program should now compile without any warning and contain fewer bugs.
This procedure lets you take advantage of C++ strict type checking, thus reducing the number of bugs. In particular, this procedure forces you to include stdlib.hor you will get
malloc was not declared within this scope
and also forces you to cast the result of malloc or you will get
invalid conversion from void* to T*
or what ever your target type is.
The only benefits from writing in C instead of C++ I can find are
C has a well specified ABI
C++ may generate more code [exceptions, RTTI, templates, runtime polymorphism]
Notice that the second cons should in the ideal case disappear when using the subset common to C together with the static polymorphic feature.
For those that finds C++ strict rules inconvenient, we can use the C++11 feature with inferred type
auto memblock=static_cast<T*>(malloc(n*sizeof(T))); //Mult may overflow...
I prefer to do the cast, but not manually. My favorite is using g_new and g_new0 macros from glib. If glib is not used, I would add similar macros. Those macros reduce code duplication without compromising type safety. If you get the type wrong, you would get an implicit cast between non-void pointers, which would cause a warning (error in C++). If you forget to include the header that defines g_new and g_new0, you would get an error. g_new and g_new0 both take the same arguments, unlike malloc that takes fewer arguments than calloc. Just add 0 to get zero-initialized memory. The code can be compiled with a C++ compiler without changes.
Casting is only for C++ not C.In case you are using a C++ compiler you better change it to C compiler.
The casting of malloc is unnecessary in C but mandatory in C++.
Casting is unnecessary in C because of:
void * is automatically and safely promoted to any other pointer type in the case of C.
It can hide an error if you forgot to include <stdlib.h>. This can cause crashes.
If pointers and integers are differently sized, then you're hiding a warning by casting and might lose bits of your returned address.
If the type of the pointer is changed at its declaration, one may also need to change all lines where malloc is called and cast.
On the other hand, casting may increase the portability of your program. i.e, it allows a C program or function to compile as C++.
The concept behind void pointer is that it can be casted to any data type that is why malloc returns void. Also you must be aware of automatic typecasting. So it is not mandatory to cast the pointer though you must do it. It helps in keeping the code clean and helps debugging
A void pointer is a generic pointer and C supports implicit conversion from a void pointer type to other types, so there is no need of explicitly typecasting it.
However, if you want the same code work perfectly compatible on a C++ platform, which does not support implicit conversion, you need to do the typecasting, so it all depends on usability.
As other stated, it is not needed for C, but for C++.
Including the cast may allow a C program or function to compile as C++.
In C it is unnecessary, as void * is automatically and safely promoted to any other pointer type.
But if you cast then, it can hide an error if you forgot to include
stdlib.h. This can cause crashes (or, worse, not cause a crash
until way later in some totally different part of the code).
Because stdlib.h contains the prototype for malloc is found. In the
absence of a prototype for malloc, the standard requires that the C
compiler assumes malloc returns an int. If there is no cast, a
warning is issued when this integer is assigned to the pointer;
however, with the cast, this warning is not produced, hiding a bug.
The main issue with malloc is to get the right size.
The memory returned form malloc() is untyped, and it will not magically gain an effective type due to a simple cast.
I guess that both approaches are fine and the choice should depend on programmer intention.
If allocating memory for a type, then use a cast.
ptr = (T*)malloc(sizeof(T));
If allocating memory for a given pointer, then don't use a cast.
ptr = malloc(sizeof *ptr);
Ad 1
The first method assures the correct size by allocating memory for a given type, and then casting it to assure that it is assigned to the right pointer. If incorrect type of ptr is used then the compiler will issue a warning/error. If the type of ptr is changed, then the compiler will point the places where the code needs refactoring.
Moreover, the first method can be combined into a macro similar to new operator in C++.
#define NEW(T) ((T*)malloc(sizeof(T)))
...
ptr = NEW(T);
Moreover this method works if ptr is void*.
Ad 2
The second methods does not care about the types, it assures the correct size by taking it from the pointer's type. The main advantage of this method is the automatic adjustment of storage size whenever the type of ptr is changed.
It can save some time (or errors) when refactoring.
The disadvantage is that the method does not work if ptr is void* but it may be perceived as a good thing. And that it does not work with C++ so it should not be used in inlined functions in headers that are going to be used by C++ programs.
Personally, I prefer the second option.
For me, the take home and conclusion here is that casting malloc in C is totally NOT necessary but if you however cast, it wont affect malloc as malloc will still allocate to you your requested blessed memory space.
Another take home is the reason or one of the reasons people do casting and this is to enable them compile same program either in C or C++.
There may be other reasons but other reasons, almost certainly, would land you in serious trouble sooner or later.
In this question, someone suggested in a comment that I should not cast the result of malloc. i.e., I should do this:
int *sieve = malloc(sizeof(*sieve) * length);
rather than:
int *sieve = (int *) malloc(sizeof(*sieve) * length);
Why would this be the case?
TL;DR
int *sieve = (int *) malloc(sizeof(int) * length);
has two problems. The cast and that you're using the type instead of variable as argument for sizeof. Instead, do like this:
int *sieve = malloc(sizeof *sieve * length);
Long version
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 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.
It can hide an error if you forgot to include <stdlib.h>. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you're hiding a warning by casting and might lose bits of your returned address. Note: as of C99 implicit functions are gone from C, and this point is no longer relevant since there's no automatic assumption that undeclared functions return int.
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 talks about 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 de-reference 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! :)
While moving length to the front may increase visibility in some rare cases, one should also pay attention that in the general case, it should be better to write the expression as:
int *sieve = malloc(sizeof *sieve * length);
Since keeping the sizeof first, in this case, ensures multiplication is done with at least size_t math.
Compare: malloc(sizeof *sieve * length * width) vs. malloc(length * width * sizeof *sieve) the second may overflow the length * width when width and length are smaller types than size_t.
In C, you don't need to cast the return value of malloc. The pointer to void returned by malloc is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed. A preferred alternative among the community is to use the following:
int *sieve = malloc(sizeof *sieve * length);
which additionally frees you from having to worry about changing the right-hand side of the expression if ever you change the type of sieve.
Casts are bad, as people have pointed out. Especially pointer casts.
You do cast, because:
It makes your code more portable between C and C++, and as SO experience shows, a great many programmers claim they are writing in C when they are really writing in C++ (or C plus local compiler extensions).
Failing to do so can hide an error: note all the SO examples of confusing when to write type * versus type **.
The idea that it keeps you from noticing you failed to #include an appropriate header file misses the forest for the trees. It's the same as saying "don't worry about the fact you failed to ask the compiler to complain about not seeing prototypes -- that pesky stdlib.h is the REAL important thing to remember!"
It forces an extra cognitive cross-check. It puts the (alleged) desired type right next to the arithmetic you're doing for the raw size of that variable. I bet you could do an SO study that shows that malloc() bugs are caught much faster when there's a cast. As with assertions, annotations that reveal intent decrease bugs.
Repeating yourself in a way that the machine can check is often a great idea. In fact, that's what an assertion is, and this use of cast is an assertion. Assertions are still the most general technique we have for getting code correct, since Turing came up with the idea so many years ago.
As others stated, it is not needed for C, but necessary for C++. If you think you are going to compile your C code with a C++ compiler, for whatever reasons, you can use a macro instead, like:
#ifdef __cplusplus
# define MALLOC(type) ((type *)malloc(sizeof(type)))
# define CALLOC(count, type) ((type *)calloc(count, sizeof(type)))
#else
# define MALLOC(type) (malloc(sizeof(type)))
# define CALLOC(count, type) (calloc(count, sizeof(type)))
#endif
# define FREE(pointer) free(pointer)
That way you can still write it in a very compact way:
int *sieve = MALLOC(int); // allocate single int => compare to stack int sieve = ???;
int *sieve_arr = CALLOC(4, int); // allocate 4 times size of int => compare to stack (int sieve_arr[4] = {0, 0, 0, 0};
// do something with the ptr or the value
FREE(sieve);
FREE(sieve_arr);
and it will compile for C and C++.
From the Wikipedia:
Advantages to casting
Including the cast may allow a C program or function to compile as C++.
The cast allows for pre-1989 versions of malloc that originally returned a char *.
Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call (although modern compilers and static analyzers can warn on such behaviour without requiring the cast).
Disadvantages to casting
Under the ANSI C standard, the cast is redundant.
Adding the cast may mask failure to include the header stdlib.h, in
which the prototype for malloc is found. In the absence of a
prototype for malloc, the standard requires that the C compiler
assume malloc returns an int. If there is no cast, a warning is
issued when this integer is assigned to the pointer; however, with
the cast, this warning is not produced, hiding a bug. On certain
architectures and data models (such as LP64 on 64-bit systems, where
long and pointers are 64-bit and int is 32-bit), this error can
actually result in undefined behaviour, as the implicitly declared
malloc returns a 32-bit value whereas the actually defined function
returns a 64-bit value. Depending on calling conventions and memory
layout, this may result in stack smashing. This issue is less likely
to go unnoticed in modern compilers, as they uniformly produce
warnings that an undeclared function has been used, so a warning will
still appear. For example, GCC's default behaviour is to show a
warning that reads "incompatible implicit declaration of built-in
function" regardless of whether the cast is present or not.
If the type of the pointer is changed at its declaration, one may
also, need to change all lines where malloc is called and cast.
Although malloc without casting is preferred method and most experienced programmers choose it, you should use whichever you like having aware of the issues.
i.e: If you need to compile C program as C++ (Although it is a separate language) you must cast the result of use malloc.
In C you can implicitly convert a void pointer to any other kind of pointer, so a cast is not necessary. Using one may suggest to the casual observer that there is some reason why one is needed, which may be misleading.
You don't cast the result of malloc, because doing so adds pointless clutter to your code.
The most common reason why people cast the result of malloc is because they are unsure about how the C language works. That's a warning sign: if you don't know how a particular language mechanism works, then don't take a guess. Look it up or ask on Stack Overflow.
Some comments:
A void pointer can be converted to/from any other pointer type without an explicit cast (C11 6.3.2.3 and 6.5.16.1).
C++ will however not allow an implicit cast between void* and another pointer type. So in C++, the cast would have been correct. But if you program in C++, you should use new and not malloc(). And you should never compile C code using a C++ compiler.
If you need to support both C and C++ with the same source code, use compiler switches to mark the differences. Do not attempt to sate both language standards with the same code, because they are not compatible.
If a C compiler cannot find a function because you forgot to include the header, you will get a compiler/linker error about that. So if you forgot to include <stdlib.h> that's no biggie, you won't be able to build your program.
On ancient compilers that follow a version of the standard which is more than 25 years old, forgetting to include <stdlib.h> would result in dangerous behavior. Because in that ancient standard, functions without a visible prototype implicitly converted the return type to int. Casting the result from malloc explicitly would then hide away this bug.
But that is really a non-issue. You aren't using a 25 years old computer, so why would you use a 25 years old compiler?
In C you get an implicit conversion from void * to any other (data) pointer.
Casting the value returned by malloc() is not necessary now, but I'd like to add one point that seems no one has pointed out:
In the ancient days, that is, before ANSI C provides the void * as the generic type of pointers, char * is the type for such usage. In that case, the cast can shut down the compiler warnings.
Reference: C FAQ
Just adding my experience, studying computer engineering I see that the two or three professors that I have seen writing in C always cast malloc, however the one I asked (with an immense CV and understanding of C) told me that it is absolutely unnecessary but only used to be absolutely specific, and to get the students into the mentality of being absolutely specific. Essentially casting will not change anything in how it works, it does exactly what it says, allocates memory, and casting does not effect it, you get the same memory, and even if you cast it to something else by mistake (and somehow evade compiler errors) C will access it the same way.
Edit: Casting has a certain point. When you use array notation, the code generated has to know how many memory places it has to advance to reach the beginning of the next element, this is achieved through casting. This way you know that for a double you go 8 bytes ahead while for an int you go 4, and so on. Thus it has no effect if you use pointer notation, in array notation it becomes necessary.
It is not mandatory to cast the results of malloc, since it returns void* , and a void* can be pointed to any datatype.
This is what The GNU C Library Reference manual says:
You can store the result of malloc into any pointer variable without a
cast, because ISO C automatically converts the type void * to another
type of pointer when necessary. But the cast is necessary in contexts
other than assignment operators or if you might want your code to run
in traditional C.
And indeed the ISO C11 standard (p347) says so:
The pointer returned if the allocation succeeds is suitably aligned so
that it may be assigned to a pointer to any type of object with a
fundamental alignment requirement and then used to access such an
object or an array of such objects in the space allocated (until the
space is explicitly deallocated)
A void pointer is a generic object pointer and C supports implicit conversion from a void pointer type to other types, so there is no need of explicitly typecasting it.
However, if you want the same code work perfectly compatible on a C++ platform, which does not support implicit conversion, you need to do the typecasting, so it all depends on usability.
The returned type is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
It depends on the programming language and compiler. If you use malloc in C, there is no need to type cast it, as it will automatically type cast. However, if you are using C++, then you should type cast because malloc will return a void* type.
In the C language, a void pointer can be assigned to any pointer, which is why you should not use a type cast. If you want "type safe" allocation, I can recommend the following macro functions, which I always use in my C projects:
#include <stdlib.h>
#define NEW_ARRAY(ptr, n) (ptr) = malloc((n) * sizeof *(ptr))
#define NEW(ptr) NEW_ARRAY((ptr), 1)
With these in place you can simply say
NEW_ARRAY(sieve, length);
For non-dynamic arrays, the third must-have function macro is
#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])
which makes array loops safer and more convenient:
int i, a[100];
for (i = 0; i < LEN(a); i++) {
...
}
People used to GCC and Clang are spoiled. It's not all that good out there.
I have been pretty horrified over the years by the staggeringly aged compilers I've been required to use. Often companies and managers adopt an ultra-conservative approach to changing compilers and will not even test if a new compiler ( with better standards compliance and code optimization ) will work in their system. The practical reality for working developers is that when you're coding you need to cover your bases and, unfortunately, casting mallocs is a good habit if you cannot control what compiler may be applied to your code.
I would also suggest that many organizations apply a coding standard of their own and that that should be the method people follow if it is defined. In the absence of explicit guidance I tend to go for most likely to compile everywhere, rather than slavish adherence to a standard.
The argument that it's not necessary under current standards is quite valid. But that argument omits the practicalities of the real world. We do not code in a world ruled exclusively by the standard of the day, but by the practicalities of what I like to call "local management's reality field". And that's bent and twisted more than space time ever was. :-)
YMMV.
I tend to think of casting malloc as a defensive operation. Not pretty, not perfect, but generally safe. ( Honestly, if you've not included stdlib.h then you've way more problems than casting malloc ! ).
This question is subject of opinion-based abuse.
Sometimes I notice comments like that:
Don't cast the result of malloc
or
Why you don't cast the result of malloc
on questions where OP uses casting. The comments itself contain a hyperlink to this question.
That is in any possible manner inappropriate and incorrect as well. There is no right and no wrong when it is truly a matter of one's own coding-style.
Why is this happening?
It's based upon two reasons:
This question is indeed opinion-based. Technically, the question should have been closed as opinion-based years ago. A "Do I" or "Don't I" or equivalent "Should I" or "Shouldn't I" question, you just can't answer focused without an attitude of one's own opinion. One of the reason to close a question is because it "might lead to opinion-based answers" as it is well shown here.
Many answers (including the most apparent and accepted answer of #unwind) are either completely or almost entirely opinion-based (f.e. a mysterious "clutter" that would be added to your code if you do casting or repeating yourself would be bad) and show a clear and focused tendency to omit the cast. They argue about the redundancy of the cast on one side but also and even worse argue to solve a bug caused by a bug/failure of programming itself - to not #include <stdlib.h> if one want to use malloc().
I want to bring a true view of some points discussed, with less of my personal opinion. A few points need to be noted especially:
Such a very susceptible question to fall into one's own opinion needs an answer with neutral pros and cons. Not only cons or pros.
A good overview of pros and cons is listed in this answer:
https://stackoverflow.com/a/33047365/12139179
(I personally consider this because of that reason the best answer, so far.)
One reason which is encountered at most to reason the omission of the cast is that the cast might hide a bug.
If someone uses an implicit declared malloc() that returns int (implicit functions are gone from the standard since C99) and sizeof(int) != sizeof(int*), as shown in this question
Why does this code segfault on 64-bit architecture but work fine on 32-bit?
the cast would hide a bug.
While this is true, it only shows half of the story as the omission of the cast would only be a forward-bringing solution to an even bigger bug - not including stdlib.h when using malloc().
This will never be a serious issue, If you,
Use a compiler compliant to C99 or above (which is recommended and should be mandatory), and
Aren't so absent to forgot to include stdlib.h, when you want to use malloc() in your code, which is a huge bug itself.
Some people argue about C++ compliance of C code, as the cast is obliged in C++.
First of all to say in general: Compiling C code with a C++ compiler is not a good practice.
C and C++ are in fact two completely different languages with different semantics.
But If you really want/need to make C code compliant to C++ and vice versa use compiler switches instead of any cast.
Since the cast is with tendency declared as redundant or even harmful, I want to take a focus on these questions, which give good reasons why casting can be useful or even necessary:
https://stackoverflow.com/a/34094068/12139179
https://stackoverflow.com/a/36297486/12139179
https://stackoverflow.com/a/33044300/12139179
The cast can be non-beneficial when your code, respectively the type of the assigned pointer (and with that the type of the cast), changes, although this is in most cases unlikely. Then you would need to maintain/change all casts too and if you have a few thousand calls to memory-management functions in your code, this can really summarizing up and decrease the maintenance efficiency.
Summary:
Fact is, that the cast is redundant per the C standard (already since ANSI-C (C89/C90)) if the assigned pointer point to an object of fundamental alignment requirement (which includes the most of all objects).
You don't need to do the cast as the pointer is automatically aligned in this case:
"The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated)."
Source: C18, §7.22.3/1
"A fundamental alignment is a valid alignment less than or equal to _Alignof (max_align_t). Fundamental alignments shall be supported by the implementation for objects of all storage durations. The alignment requirements of the following types shall be fundamental alignments:
— all atomic, qualified, or unqualified basic types;
— all atomic, qualified, or unqualified enumerated types;
— all atomic, qualified, or unqualified pointer types;
— all array types whose element type has a fundamental alignment requirement;57)
— all types specified in Clause 7 as complete object types;
— all structure or union types all of whose elements have types with fundamental alignment requirements and none of whose elements have an alignment specifier specifying an alignment that is not a fundamental alignment.
As specified in 6.2.1, the later declaration might hide the prior declaration."
Source: C18, §6.2.8/2
However, if you allocate memory for an implementation-defined object of extended alignment requirement, the cast would be needed.
An extended alignment is represented by an alignment greater than _Alignof (max_align_t). It is implementation-defined whether any extended alignments are supported and the storage durations for which they are supported. A type having an extended alignment requirement is an over-aligned type.58)
Source. C18, §6.2.8/3
Everything else is a matter of the specific use case and one's own opinion.
Please be careful how you educate yourself.
I recommend you to read all of the answers made so far carefully first (as well as their comments which may point at a failure) and then build your own opinion if you or if you not cast the result of malloc() at a specific case.
Please note:
There is no right and wrong answer to that question. It is a matter of style and you yourself decide which way you choose (if you aren't forced to by education or job of course). Please be aware of that and don't let trick you.
Last note: I voted to lately close this question as opinion-based, which is indeed needed since years. If you got the close/reopen privilege I would like to invite you to do so, too.
No, you don't cast the result of malloc().
In general, you don't cast to or from void *.
A typical reason given for not doing so is that failure to #include <stdlib.h> could go unnoticed. This isn't an issue anymore for a long time now as C99 made implicit function declarations illegal, so if your compiler conforms to at least C99, you will get a diagnostic message.
But there's a much stronger reason not to introduce unnecessary pointer casts:
In C, a pointer cast is almost always an error. This is because of the following rule (§6.5 p7 in N1570, the latest draft for C11):
An object shall have its stored value accessed only by an lvalue expression that has one of
the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the
object,
— a type that is the signed or unsigned type corresponding to a qualified version of the
effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its
members (including, recursively, a member of a subaggregate or contained union), or
— a character type.
This is also known as the strict aliasing rule. So the following code is undefined behavior:
long x = 5;
double *p = (double *)&x;
double y = *p;
And, sometimes surprisingly, the following is as well:
struct foo { int x; };
struct bar { int x; int y; };
struct bar b = { 1, 2};
struct foo *p = (struct foo *)&b;
int z = p->x;
Sometimes, you do need to cast pointers, but given the strict aliasing rule, you have to be very careful with it. So, any occurrence of a pointer cast in your code is a place you have to double-check for its validity. Therefore, you never write an unnecessary pointer cast.
tl;dr
In a nutshell: Because in C, any occurrence of a pointer cast should raise a red flag for code requiring special attention, you should never write unnecessary pointer casts.
Side notes:
There are cases where you actually need a cast to void *, e.g. if you want to print a pointer:
int x = 5;
printf("%p\n", (void *)&x);
The cast is necessary here, because printf() is a variadic function, so implicit conversions don't work.
In C++, the situation is different. Casting pointer types is somewhat common (and correct) when dealing with objects of derived classes. Therefore, it makes sense that in C++, the conversion to and from void * is not implicit. C++ has a whole set of different flavors of casting.
I put in the cast simply to show disapproval of the ugly hole in the type system, which allows code such as the following snippet to compile without diagnostics, even though no casts are used to bring about the bad conversion:
double d;
void *p = &d;
int *q = p;
I wish that didn't exist (and it doesn't in C++) and so I cast. It represents my taste, and my programming politics. I'm not only casting a pointer, but effectively, casting a ballot, and casting out demons of stupidity. If I can't actually cast out stupidity, then at least let me express the wish to do so with a gesture of protest.
In fact, a good practice is to wrap malloc (and friends) with functions that return unsigned char *, and basically never to use void * in your code. If you need a generic pointer-to-any-object, use a char * or unsigned char *, and have casts in both directions. The one relaxation that can be indulged, perhaps, is using functions like memset and memcpy without casts.
On the topic of casting and C++ compatibility, if you write your code so that it compiles as both C and C++ (in which case you have to cast the return value of malloc when assigning it to something other than void *), you can do a very helpful thing for yourself: you can use macros for casting which translate to C++ style casts when compiling as C++, but reduce to a C cast when compiling as C:
/* In a header somewhere */
#ifdef __cplusplus
#define strip_qual(TYPE, EXPR) (const_cast<TYPE>(EXPR))
#define convert(TYPE, EXPR) (static_cast<TYPE>(EXPR))
#define coerce(TYPE, EXPR) (reinterpret_cast<TYPE>(EXPR))
#else
#define strip_qual(TYPE, EXPR) ((TYPE) (EXPR))
#define convert(TYPE, EXPR) ((TYPE) (EXPR))
#define coerce(TYPE, EXPR) ((TYPE) (EXPR))
#endif
If you adhere to these macros, then a simple grep search of your code base for these identifiers will show you where all your casts are, so you can review whether any of them are incorrect.
Then, going forward, if you regularly compile the code with C++, it will enforce the use of an appropriate cast. For instance, if you use strip_qual just to remove a const or volatile, but the program changes in such a way that a type conversion is now involved, you will get a diagnostic, and you will have to use a combination of casts to get the desired conversion.
To help you adhere to these macros, the the GNU C++ (not C!) compiler has a beautiful feature: an optional diagnostic which is produced for all occurrences of C style casts.
-Wold-style-cast (C++ and Objective-C++ only)
Warn if an old-style (C-style) cast to a non-void type is used
within a C++ program. The new-style casts (dynamic_cast,
static_cast, reinterpret_cast, and const_cast) are less vulnerable
to unintended effects and much easier to search for.
If your C code compiles as C++, you can use this -Wold-style-cast option to find out all occurrences of the (type) casting syntax that may creep into the code, and follow up on these diagnostics by replacing it with an appropriate choice from among the above macros (or a combination, if necessary).
This treatment of conversions is the single largest standalone technical justification for working in a "Clean C": the combined C and C++ dialect, which in turn technically justifies casting the return value of malloc.
The best thing to do when programming in C whenever it is possible:
Make your program compile through a C compiler with all warnings turned on -Wall and fix all errors and warnings
Make sure there are no variables declared as auto
Then compile it using a C++ compiler with -Wall and -std=c++11. Fix all errors and warnings.
Now compile using the C compiler again. Your program should now compile without any warning and contain fewer bugs.
This procedure lets you take advantage of C++ strict type checking, thus reducing the number of bugs. In particular, this procedure forces you to include stdlib.hor you will get
malloc was not declared within this scope
and also forces you to cast the result of malloc or you will get
invalid conversion from void* to T*
or what ever your target type is.
The only benefits from writing in C instead of C++ I can find are
C has a well specified ABI
C++ may generate more code [exceptions, RTTI, templates, runtime polymorphism]
Notice that the second cons should in the ideal case disappear when using the subset common to C together with the static polymorphic feature.
For those that finds C++ strict rules inconvenient, we can use the C++11 feature with inferred type
auto memblock=static_cast<T*>(malloc(n*sizeof(T))); //Mult may overflow...
I prefer to do the cast, but not manually. My favorite is using g_new and g_new0 macros from glib. If glib is not used, I would add similar macros. Those macros reduce code duplication without compromising type safety. If you get the type wrong, you would get an implicit cast between non-void pointers, which would cause a warning (error in C++). If you forget to include the header that defines g_new and g_new0, you would get an error. g_new and g_new0 both take the same arguments, unlike malloc that takes fewer arguments than calloc. Just add 0 to get zero-initialized memory. The code can be compiled with a C++ compiler without changes.
Casting is only for C++ not C.In case you are using a C++ compiler you better change it to C compiler.
The casting of malloc is unnecessary in C but mandatory in C++.
Casting is unnecessary in C because of:
void * is automatically and safely promoted to any other pointer type in the case of C.
It can hide an error if you forgot to include <stdlib.h>. This can cause crashes.
If pointers and integers are differently sized, then you're hiding a warning by casting and might lose bits of your returned address.
If the type of the pointer is changed at its declaration, one may also need to change all lines where malloc is called and cast.
On the other hand, casting may increase the portability of your program. i.e, it allows a C program or function to compile as C++.
The concept behind void pointer is that it can be casted to any data type that is why malloc returns void. Also you must be aware of automatic typecasting. So it is not mandatory to cast the pointer though you must do it. It helps in keeping the code clean and helps debugging
A void pointer is a generic pointer and C supports implicit conversion from a void pointer type to other types, so there is no need of explicitly typecasting it.
However, if you want the same code work perfectly compatible on a C++ platform, which does not support implicit conversion, you need to do the typecasting, so it all depends on usability.
As other stated, it is not needed for C, but for C++.
Including the cast may allow a C program or function to compile as C++.
In C it is unnecessary, as void * is automatically and safely promoted to any other pointer type.
But if you cast then, it can hide an error if you forgot to include
stdlib.h. This can cause crashes (or, worse, not cause a crash
until way later in some totally different part of the code).
Because stdlib.h contains the prototype for malloc is found. In the
absence of a prototype for malloc, the standard requires that the C
compiler assumes malloc returns an int. If there is no cast, a
warning is issued when this integer is assigned to the pointer;
however, with the cast, this warning is not produced, hiding a bug.
The main issue with malloc is to get the right size.
The memory returned form malloc() is untyped, and it will not magically gain an effective type due to a simple cast.
I guess that both approaches are fine and the choice should depend on programmer intention.
If allocating memory for a type, then use a cast.
ptr = (T*)malloc(sizeof(T));
If allocating memory for a given pointer, then don't use a cast.
ptr = malloc(sizeof *ptr);
Ad 1
The first method assures the correct size by allocating memory for a given type, and then casting it to assure that it is assigned to the right pointer. If incorrect type of ptr is used then the compiler will issue a warning/error. If the type of ptr is changed, then the compiler will point the places where the code needs refactoring.
Moreover, the first method can be combined into a macro similar to new operator in C++.
#define NEW(T) ((T*)malloc(sizeof(T)))
...
ptr = NEW(T);
Moreover this method works if ptr is void*.
Ad 2
The second methods does not care about the types, it assures the correct size by taking it from the pointer's type. The main advantage of this method is the automatic adjustment of storage size whenever the type of ptr is changed.
It can save some time (or errors) when refactoring.
The disadvantage is that the method does not work if ptr is void* but it may be perceived as a good thing. And that it does not work with C++ so it should not be used in inlined functions in headers that are going to be used by C++ programs.
Personally, I prefer the second option.
For me, the take home and conclusion here is that casting malloc in C is totally NOT necessary but if you however cast, it wont affect malloc as malloc will still allocate to you your requested blessed memory space.
Another take home is the reason or one of the reasons people do casting and this is to enable them compile same program either in C or C++.
There may be other reasons but other reasons, almost certainly, would land you in serious trouble sooner or later.
In this question, someone suggested in a comment that I should not cast the result of malloc. i.e., I should do this:
int *sieve = malloc(sizeof(*sieve) * length);
rather than:
int *sieve = (int *) malloc(sizeof(*sieve) * length);
Why would this be the case?
TL;DR
int *sieve = (int *) malloc(sizeof(int) * length);
has two problems. The cast and that you're using the type instead of variable as argument for sizeof. Instead, do like this:
int *sieve = malloc(sizeof *sieve * length);
Long version
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 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.
It can hide an error if you forgot to include <stdlib.h>. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you're hiding a warning by casting and might lose bits of your returned address. Note: as of C99 implicit functions are gone from C, and this point is no longer relevant since there's no automatic assumption that undeclared functions return int.
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 talks about 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 de-reference 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! :)
While moving length to the front may increase visibility in some rare cases, one should also pay attention that in the general case, it should be better to write the expression as:
int *sieve = malloc(sizeof *sieve * length);
Since keeping the sizeof first, in this case, ensures multiplication is done with at least size_t math.
Compare: malloc(sizeof *sieve * length * width) vs. malloc(length * width * sizeof *sieve) the second may overflow the length * width when width and length are smaller types than size_t.
In C, you don't need to cast the return value of malloc. The pointer to void returned by malloc is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed. A preferred alternative among the community is to use the following:
int *sieve = malloc(sizeof *sieve * length);
which additionally frees you from having to worry about changing the right-hand side of the expression if ever you change the type of sieve.
Casts are bad, as people have pointed out. Especially pointer casts.
You do cast, because:
It makes your code more portable between C and C++, and as SO experience shows, a great many programmers claim they are writing in C when they are really writing in C++ (or C plus local compiler extensions).
Failing to do so can hide an error: note all the SO examples of confusing when to write type * versus type **.
The idea that it keeps you from noticing you failed to #include an appropriate header file misses the forest for the trees. It's the same as saying "don't worry about the fact you failed to ask the compiler to complain about not seeing prototypes -- that pesky stdlib.h is the REAL important thing to remember!"
It forces an extra cognitive cross-check. It puts the (alleged) desired type right next to the arithmetic you're doing for the raw size of that variable. I bet you could do an SO study that shows that malloc() bugs are caught much faster when there's a cast. As with assertions, annotations that reveal intent decrease bugs.
Repeating yourself in a way that the machine can check is often a great idea. In fact, that's what an assertion is, and this use of cast is an assertion. Assertions are still the most general technique we have for getting code correct, since Turing came up with the idea so many years ago.
As others stated, it is not needed for C, but necessary for C++. If you think you are going to compile your C code with a C++ compiler, for whatever reasons, you can use a macro instead, like:
#ifdef __cplusplus
# define MALLOC(type) ((type *)malloc(sizeof(type)))
# define CALLOC(count, type) ((type *)calloc(count, sizeof(type)))
#else
# define MALLOC(type) (malloc(sizeof(type)))
# define CALLOC(count, type) (calloc(count, sizeof(type)))
#endif
# define FREE(pointer) free(pointer)
That way you can still write it in a very compact way:
int *sieve = MALLOC(int); // allocate single int => compare to stack int sieve = ???;
int *sieve_arr = CALLOC(4, int); // allocate 4 times size of int => compare to stack (int sieve_arr[4] = {0, 0, 0, 0};
// do something with the ptr or the value
FREE(sieve);
FREE(sieve_arr);
and it will compile for C and C++.
From the Wikipedia:
Advantages to casting
Including the cast may allow a C program or function to compile as C++.
The cast allows for pre-1989 versions of malloc that originally returned a char *.
Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call (although modern compilers and static analyzers can warn on such behaviour without requiring the cast).
Disadvantages to casting
Under the ANSI C standard, the cast is redundant.
Adding the cast may mask failure to include the header stdlib.h, in
which the prototype for malloc is found. In the absence of a
prototype for malloc, the standard requires that the C compiler
assume malloc returns an int. If there is no cast, a warning is
issued when this integer is assigned to the pointer; however, with
the cast, this warning is not produced, hiding a bug. On certain
architectures and data models (such as LP64 on 64-bit systems, where
long and pointers are 64-bit and int is 32-bit), this error can
actually result in undefined behaviour, as the implicitly declared
malloc returns a 32-bit value whereas the actually defined function
returns a 64-bit value. Depending on calling conventions and memory
layout, this may result in stack smashing. This issue is less likely
to go unnoticed in modern compilers, as they uniformly produce
warnings that an undeclared function has been used, so a warning will
still appear. For example, GCC's default behaviour is to show a
warning that reads "incompatible implicit declaration of built-in
function" regardless of whether the cast is present or not.
If the type of the pointer is changed at its declaration, one may
also, need to change all lines where malloc is called and cast.
Although malloc without casting is preferred method and most experienced programmers choose it, you should use whichever you like having aware of the issues.
i.e: If you need to compile C program as C++ (Although it is a separate language) you must cast the result of use malloc.
In C you can implicitly convert a void pointer to any other kind of pointer, so a cast is not necessary. Using one may suggest to the casual observer that there is some reason why one is needed, which may be misleading.
You don't cast the result of malloc, because doing so adds pointless clutter to your code.
The most common reason why people cast the result of malloc is because they are unsure about how the C language works. That's a warning sign: if you don't know how a particular language mechanism works, then don't take a guess. Look it up or ask on Stack Overflow.
Some comments:
A void pointer can be converted to/from any other pointer type without an explicit cast (C11 6.3.2.3 and 6.5.16.1).
C++ will however not allow an implicit cast between void* and another pointer type. So in C++, the cast would have been correct. But if you program in C++, you should use new and not malloc(). And you should never compile C code using a C++ compiler.
If you need to support both C and C++ with the same source code, use compiler switches to mark the differences. Do not attempt to sate both language standards with the same code, because they are not compatible.
If a C compiler cannot find a function because you forgot to include the header, you will get a compiler/linker error about that. So if you forgot to include <stdlib.h> that's no biggie, you won't be able to build your program.
On ancient compilers that follow a version of the standard which is more than 25 years old, forgetting to include <stdlib.h> would result in dangerous behavior. Because in that ancient standard, functions without a visible prototype implicitly converted the return type to int. Casting the result from malloc explicitly would then hide away this bug.
But that is really a non-issue. You aren't using a 25 years old computer, so why would you use a 25 years old compiler?
In C you get an implicit conversion from void * to any other (data) pointer.
Casting the value returned by malloc() is not necessary now, but I'd like to add one point that seems no one has pointed out:
In the ancient days, that is, before ANSI C provides the void * as the generic type of pointers, char * is the type for such usage. In that case, the cast can shut down the compiler warnings.
Reference: C FAQ
Just adding my experience, studying computer engineering I see that the two or three professors that I have seen writing in C always cast malloc, however the one I asked (with an immense CV and understanding of C) told me that it is absolutely unnecessary but only used to be absolutely specific, and to get the students into the mentality of being absolutely specific. Essentially casting will not change anything in how it works, it does exactly what it says, allocates memory, and casting does not effect it, you get the same memory, and even if you cast it to something else by mistake (and somehow evade compiler errors) C will access it the same way.
Edit: Casting has a certain point. When you use array notation, the code generated has to know how many memory places it has to advance to reach the beginning of the next element, this is achieved through casting. This way you know that for a double you go 8 bytes ahead while for an int you go 4, and so on. Thus it has no effect if you use pointer notation, in array notation it becomes necessary.
It is not mandatory to cast the results of malloc, since it returns void* , and a void* can be pointed to any datatype.
This is what The GNU C Library Reference manual says:
You can store the result of malloc into any pointer variable without a
cast, because ISO C automatically converts the type void * to another
type of pointer when necessary. But the cast is necessary in contexts
other than assignment operators or if you might want your code to run
in traditional C.
And indeed the ISO C11 standard (p347) says so:
The pointer returned if the allocation succeeds is suitably aligned so
that it may be assigned to a pointer to any type of object with a
fundamental alignment requirement and then used to access such an
object or an array of such objects in the space allocated (until the
space is explicitly deallocated)
A void pointer is a generic object pointer and C supports implicit conversion from a void pointer type to other types, so there is no need of explicitly typecasting it.
However, if you want the same code work perfectly compatible on a C++ platform, which does not support implicit conversion, you need to do the typecasting, so it all depends on usability.
The returned type is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
It depends on the programming language and compiler. If you use malloc in C, there is no need to type cast it, as it will automatically type cast. However, if you are using C++, then you should type cast because malloc will return a void* type.
In the C language, a void pointer can be assigned to any pointer, which is why you should not use a type cast. If you want "type safe" allocation, I can recommend the following macro functions, which I always use in my C projects:
#include <stdlib.h>
#define NEW_ARRAY(ptr, n) (ptr) = malloc((n) * sizeof *(ptr))
#define NEW(ptr) NEW_ARRAY((ptr), 1)
With these in place you can simply say
NEW_ARRAY(sieve, length);
For non-dynamic arrays, the third must-have function macro is
#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])
which makes array loops safer and more convenient:
int i, a[100];
for (i = 0; i < LEN(a); i++) {
...
}
People used to GCC and Clang are spoiled. It's not all that good out there.
I have been pretty horrified over the years by the staggeringly aged compilers I've been required to use. Often companies and managers adopt an ultra-conservative approach to changing compilers and will not even test if a new compiler ( with better standards compliance and code optimization ) will work in their system. The practical reality for working developers is that when you're coding you need to cover your bases and, unfortunately, casting mallocs is a good habit if you cannot control what compiler may be applied to your code.
I would also suggest that many organizations apply a coding standard of their own and that that should be the method people follow if it is defined. In the absence of explicit guidance I tend to go for most likely to compile everywhere, rather than slavish adherence to a standard.
The argument that it's not necessary under current standards is quite valid. But that argument omits the practicalities of the real world. We do not code in a world ruled exclusively by the standard of the day, but by the practicalities of what I like to call "local management's reality field". And that's bent and twisted more than space time ever was. :-)
YMMV.
I tend to think of casting malloc as a defensive operation. Not pretty, not perfect, but generally safe. ( Honestly, if you've not included stdlib.h then you've way more problems than casting malloc ! ).
This question is subject of opinion-based abuse.
Sometimes I notice comments like that:
Don't cast the result of malloc
or
Why you don't cast the result of malloc
on questions where OP uses casting. The comments itself contain a hyperlink to this question.
That is in any possible manner inappropriate and incorrect as well. There is no right and no wrong when it is truly a matter of one's own coding-style.
Why is this happening?
It's based upon two reasons:
This question is indeed opinion-based. Technically, the question should have been closed as opinion-based years ago. A "Do I" or "Don't I" or equivalent "Should I" or "Shouldn't I" question, you just can't answer focused without an attitude of one's own opinion. One of the reason to close a question is because it "might lead to opinion-based answers" as it is well shown here.
Many answers (including the most apparent and accepted answer of #unwind) are either completely or almost entirely opinion-based (f.e. a mysterious "clutter" that would be added to your code if you do casting or repeating yourself would be bad) and show a clear and focused tendency to omit the cast. They argue about the redundancy of the cast on one side but also and even worse argue to solve a bug caused by a bug/failure of programming itself - to not #include <stdlib.h> if one want to use malloc().
I want to bring a true view of some points discussed, with less of my personal opinion. A few points need to be noted especially:
Such a very susceptible question to fall into one's own opinion needs an answer with neutral pros and cons. Not only cons or pros.
A good overview of pros and cons is listed in this answer:
https://stackoverflow.com/a/33047365/12139179
(I personally consider this because of that reason the best answer, so far.)
One reason which is encountered at most to reason the omission of the cast is that the cast might hide a bug.
If someone uses an implicit declared malloc() that returns int (implicit functions are gone from the standard since C99) and sizeof(int) != sizeof(int*), as shown in this question
Why does this code segfault on 64-bit architecture but work fine on 32-bit?
the cast would hide a bug.
While this is true, it only shows half of the story as the omission of the cast would only be a forward-bringing solution to an even bigger bug - not including stdlib.h when using malloc().
This will never be a serious issue, If you,
Use a compiler compliant to C99 or above (which is recommended and should be mandatory), and
Aren't so absent to forgot to include stdlib.h, when you want to use malloc() in your code, which is a huge bug itself.
Some people argue about C++ compliance of C code, as the cast is obliged in C++.
First of all to say in general: Compiling C code with a C++ compiler is not a good practice.
C and C++ are in fact two completely different languages with different semantics.
But If you really want/need to make C code compliant to C++ and vice versa use compiler switches instead of any cast.
Since the cast is with tendency declared as redundant or even harmful, I want to take a focus on these questions, which give good reasons why casting can be useful or even necessary:
https://stackoverflow.com/a/34094068/12139179
https://stackoverflow.com/a/36297486/12139179
https://stackoverflow.com/a/33044300/12139179
The cast can be non-beneficial when your code, respectively the type of the assigned pointer (and with that the type of the cast), changes, although this is in most cases unlikely. Then you would need to maintain/change all casts too and if you have a few thousand calls to memory-management functions in your code, this can really summarizing up and decrease the maintenance efficiency.
Summary:
Fact is, that the cast is redundant per the C standard (already since ANSI-C (C89/C90)) if the assigned pointer point to an object of fundamental alignment requirement (which includes the most of all objects).
You don't need to do the cast as the pointer is automatically aligned in this case:
"The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated)."
Source: C18, §7.22.3/1
"A fundamental alignment is a valid alignment less than or equal to _Alignof (max_align_t). Fundamental alignments shall be supported by the implementation for objects of all storage durations. The alignment requirements of the following types shall be fundamental alignments:
— all atomic, qualified, or unqualified basic types;
— all atomic, qualified, or unqualified enumerated types;
— all atomic, qualified, or unqualified pointer types;
— all array types whose element type has a fundamental alignment requirement;57)
— all types specified in Clause 7 as complete object types;
— all structure or union types all of whose elements have types with fundamental alignment requirements and none of whose elements have an alignment specifier specifying an alignment that is not a fundamental alignment.
As specified in 6.2.1, the later declaration might hide the prior declaration."
Source: C18, §6.2.8/2
However, if you allocate memory for an implementation-defined object of extended alignment requirement, the cast would be needed.
An extended alignment is represented by an alignment greater than _Alignof (max_align_t). It is implementation-defined whether any extended alignments are supported and the storage durations for which they are supported. A type having an extended alignment requirement is an over-aligned type.58)
Source. C18, §6.2.8/3
Everything else is a matter of the specific use case and one's own opinion.
Please be careful how you educate yourself.
I recommend you to read all of the answers made so far carefully first (as well as their comments which may point at a failure) and then build your own opinion if you or if you not cast the result of malloc() at a specific case.
Please note:
There is no right and wrong answer to that question. It is a matter of style and you yourself decide which way you choose (if you aren't forced to by education or job of course). Please be aware of that and don't let trick you.
Last note: I voted to lately close this question as opinion-based, which is indeed needed since years. If you got the close/reopen privilege I would like to invite you to do so, too.
No, you don't cast the result of malloc().
In general, you don't cast to or from void *.
A typical reason given for not doing so is that failure to #include <stdlib.h> could go unnoticed. This isn't an issue anymore for a long time now as C99 made implicit function declarations illegal, so if your compiler conforms to at least C99, you will get a diagnostic message.
But there's a much stronger reason not to introduce unnecessary pointer casts:
In C, a pointer cast is almost always an error. This is because of the following rule (§6.5 p7 in N1570, the latest draft for C11):
An object shall have its stored value accessed only by an lvalue expression that has one of
the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the
object,
— a type that is the signed or unsigned type corresponding to a qualified version of the
effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its
members (including, recursively, a member of a subaggregate or contained union), or
— a character type.
This is also known as the strict aliasing rule. So the following code is undefined behavior:
long x = 5;
double *p = (double *)&x;
double y = *p;
And, sometimes surprisingly, the following is as well:
struct foo { int x; };
struct bar { int x; int y; };
struct bar b = { 1, 2};
struct foo *p = (struct foo *)&b;
int z = p->x;
Sometimes, you do need to cast pointers, but given the strict aliasing rule, you have to be very careful with it. So, any occurrence of a pointer cast in your code is a place you have to double-check for its validity. Therefore, you never write an unnecessary pointer cast.
tl;dr
In a nutshell: Because in C, any occurrence of a pointer cast should raise a red flag for code requiring special attention, you should never write unnecessary pointer casts.
Side notes:
There are cases where you actually need a cast to void *, e.g. if you want to print a pointer:
int x = 5;
printf("%p\n", (void *)&x);
The cast is necessary here, because printf() is a variadic function, so implicit conversions don't work.
In C++, the situation is different. Casting pointer types is somewhat common (and correct) when dealing with objects of derived classes. Therefore, it makes sense that in C++, the conversion to and from void * is not implicit. C++ has a whole set of different flavors of casting.
I put in the cast simply to show disapproval of the ugly hole in the type system, which allows code such as the following snippet to compile without diagnostics, even though no casts are used to bring about the bad conversion:
double d;
void *p = &d;
int *q = p;
I wish that didn't exist (and it doesn't in C++) and so I cast. It represents my taste, and my programming politics. I'm not only casting a pointer, but effectively, casting a ballot, and casting out demons of stupidity. If I can't actually cast out stupidity, then at least let me express the wish to do so with a gesture of protest.
In fact, a good practice is to wrap malloc (and friends) with functions that return unsigned char *, and basically never to use void * in your code. If you need a generic pointer-to-any-object, use a char * or unsigned char *, and have casts in both directions. The one relaxation that can be indulged, perhaps, is using functions like memset and memcpy without casts.
On the topic of casting and C++ compatibility, if you write your code so that it compiles as both C and C++ (in which case you have to cast the return value of malloc when assigning it to something other than void *), you can do a very helpful thing for yourself: you can use macros for casting which translate to C++ style casts when compiling as C++, but reduce to a C cast when compiling as C:
/* In a header somewhere */
#ifdef __cplusplus
#define strip_qual(TYPE, EXPR) (const_cast<TYPE>(EXPR))
#define convert(TYPE, EXPR) (static_cast<TYPE>(EXPR))
#define coerce(TYPE, EXPR) (reinterpret_cast<TYPE>(EXPR))
#else
#define strip_qual(TYPE, EXPR) ((TYPE) (EXPR))
#define convert(TYPE, EXPR) ((TYPE) (EXPR))
#define coerce(TYPE, EXPR) ((TYPE) (EXPR))
#endif
If you adhere to these macros, then a simple grep search of your code base for these identifiers will show you where all your casts are, so you can review whether any of them are incorrect.
Then, going forward, if you regularly compile the code with C++, it will enforce the use of an appropriate cast. For instance, if you use strip_qual just to remove a const or volatile, but the program changes in such a way that a type conversion is now involved, you will get a diagnostic, and you will have to use a combination of casts to get the desired conversion.
To help you adhere to these macros, the the GNU C++ (not C!) compiler has a beautiful feature: an optional diagnostic which is produced for all occurrences of C style casts.
-Wold-style-cast (C++ and Objective-C++ only)
Warn if an old-style (C-style) cast to a non-void type is used
within a C++ program. The new-style casts (dynamic_cast,
static_cast, reinterpret_cast, and const_cast) are less vulnerable
to unintended effects and much easier to search for.
If your C code compiles as C++, you can use this -Wold-style-cast option to find out all occurrences of the (type) casting syntax that may creep into the code, and follow up on these diagnostics by replacing it with an appropriate choice from among the above macros (or a combination, if necessary).
This treatment of conversions is the single largest standalone technical justification for working in a "Clean C": the combined C and C++ dialect, which in turn technically justifies casting the return value of malloc.
The best thing to do when programming in C whenever it is possible:
Make your program compile through a C compiler with all warnings turned on -Wall and fix all errors and warnings
Make sure there are no variables declared as auto
Then compile it using a C++ compiler with -Wall and -std=c++11. Fix all errors and warnings.
Now compile using the C compiler again. Your program should now compile without any warning and contain fewer bugs.
This procedure lets you take advantage of C++ strict type checking, thus reducing the number of bugs. In particular, this procedure forces you to include stdlib.hor you will get
malloc was not declared within this scope
and also forces you to cast the result of malloc or you will get
invalid conversion from void* to T*
or what ever your target type is.
The only benefits from writing in C instead of C++ I can find are
C has a well specified ABI
C++ may generate more code [exceptions, RTTI, templates, runtime polymorphism]
Notice that the second cons should in the ideal case disappear when using the subset common to C together with the static polymorphic feature.
For those that finds C++ strict rules inconvenient, we can use the C++11 feature with inferred type
auto memblock=static_cast<T*>(malloc(n*sizeof(T))); //Mult may overflow...
I prefer to do the cast, but not manually. My favorite is using g_new and g_new0 macros from glib. If glib is not used, I would add similar macros. Those macros reduce code duplication without compromising type safety. If you get the type wrong, you would get an implicit cast between non-void pointers, which would cause a warning (error in C++). If you forget to include the header that defines g_new and g_new0, you would get an error. g_new and g_new0 both take the same arguments, unlike malloc that takes fewer arguments than calloc. Just add 0 to get zero-initialized memory. The code can be compiled with a C++ compiler without changes.
Casting is only for C++ not C.In case you are using a C++ compiler you better change it to C compiler.
The casting of malloc is unnecessary in C but mandatory in C++.
Casting is unnecessary in C because of:
void * is automatically and safely promoted to any other pointer type in the case of C.
It can hide an error if you forgot to include <stdlib.h>. This can cause crashes.
If pointers and integers are differently sized, then you're hiding a warning by casting and might lose bits of your returned address.
If the type of the pointer is changed at its declaration, one may also need to change all lines where malloc is called and cast.
On the other hand, casting may increase the portability of your program. i.e, it allows a C program or function to compile as C++.
The concept behind void pointer is that it can be casted to any data type that is why malloc returns void. Also you must be aware of automatic typecasting. So it is not mandatory to cast the pointer though you must do it. It helps in keeping the code clean and helps debugging
A void pointer is a generic pointer and C supports implicit conversion from a void pointer type to other types, so there is no need of explicitly typecasting it.
However, if you want the same code work perfectly compatible on a C++ platform, which does not support implicit conversion, you need to do the typecasting, so it all depends on usability.
As other stated, it is not needed for C, but for C++.
Including the cast may allow a C program or function to compile as C++.
In C it is unnecessary, as void * is automatically and safely promoted to any other pointer type.
But if you cast then, it can hide an error if you forgot to include
stdlib.h. This can cause crashes (or, worse, not cause a crash
until way later in some totally different part of the code).
Because stdlib.h contains the prototype for malloc is found. In the
absence of a prototype for malloc, the standard requires that the C
compiler assumes malloc returns an int. If there is no cast, a
warning is issued when this integer is assigned to the pointer;
however, with the cast, this warning is not produced, hiding a bug.
The main issue with malloc is to get the right size.
The memory returned form malloc() is untyped, and it will not magically gain an effective type due to a simple cast.
I guess that both approaches are fine and the choice should depend on programmer intention.
If allocating memory for a type, then use a cast.
ptr = (T*)malloc(sizeof(T));
If allocating memory for a given pointer, then don't use a cast.
ptr = malloc(sizeof *ptr);
Ad 1
The first method assures the correct size by allocating memory for a given type, and then casting it to assure that it is assigned to the right pointer. If incorrect type of ptr is used then the compiler will issue a warning/error. If the type of ptr is changed, then the compiler will point the places where the code needs refactoring.
Moreover, the first method can be combined into a macro similar to new operator in C++.
#define NEW(T) ((T*)malloc(sizeof(T)))
...
ptr = NEW(T);
Moreover this method works if ptr is void*.
Ad 2
The second methods does not care about the types, it assures the correct size by taking it from the pointer's type. The main advantage of this method is the automatic adjustment of storage size whenever the type of ptr is changed.
It can save some time (or errors) when refactoring.
The disadvantage is that the method does not work if ptr is void* but it may be perceived as a good thing. And that it does not work with C++ so it should not be used in inlined functions in headers that are going to be used by C++ programs.
Personally, I prefer the second option.
For me, the take home and conclusion here is that casting malloc in C is totally NOT necessary but if you however cast, it wont affect malloc as malloc will still allocate to you your requested blessed memory space.
Another take home is the reason or one of the reasons people do casting and this is to enable them compile same program either in C or C++.
There may be other reasons but other reasons, almost certainly, would land you in serious trouble sooner or later.
I was just reading about the bad practice of casting the return value of malloc. If I understood correctly, it is absolutely legal to leave the cast as it is done implicitly (and should be left, because of other problems it could generate). Well my question is, when should I then cast my values ? Is there some general rule or something ? For example, this code compiles without any errors with gcc -W -Wall (except unused bar, but that's not the point):
float foo(void) {
double bar = 4.2;
return bar;
}
int main(void) {
double bar = foo();
return 0;
}
I'm confused now. What are the good practices and the rules about casting ?
Thanks.
There are several situations that require perfectly valid casting in C. Beware of sweeping assertions like "casting is always bad design", since they are obviously and patently bogus.
One huge group of situations that critically relies on casts is arithmetic operations. The casting is required in situations when you need to force the compiler to interpret arithmetic expression within a type different from the "default" one. As in
unsigned i = ...;
unsigned long s = (unsigned long) i * i;
to avoid overflow. Or in
double d = (double) i / 5;
in order to make the compiler to switch to floating-point division. Or in
s = (unsigned) d * 3 + i;
in order to take the whole part of the floating point value. And so on (the examples are endless).
Another group of valid uses is idioms, i.e. well-established coding practices. For example, the classic C idiom when a function takes a const pointer as an input and returns a non-const pointer to the same (potentially constant) data, like the standard strstr for example. Implementing this idiom usually requires a use of a cast in order to cast away the constness of the input. Someone might call it bad design, but in reality there's no better design alternative in C. Otherwise, it wouldn't be a well-established idiom :)
Also it is worth mentioning, as an example, that a pedantically correct use of standard printf function might require casts on the arguments in general case. (Like %p format specifier expecting a void * pointer as an argument, which means that an int * argument has to be transformed into a void * in one way or another. An explicit cast is the most logical way to perform the transformation.).
Of course, there are other numerous examples of perfectly valid situations when casts are required.
The problems with casts usually arise when people use them thoughtlessly, even where they are not required (like casting the return of malloc, which is bad for more reasons than one). Or when people use casts to force the compiler to accept their bad code. Needless to say, it takes certain level of expertise to tell a valid cast situation from a bad cast one.
In some cases casts are used to make the compiler to stop issuing some annoying and unnecessary warning messages. These casts belong to the gray area between the good and the bad casts. On the one hand, unnecessary casts are bad. On the other hand, the user might not have control over the compilation settings, thus making the casts the only way to deal with the warnings.
If and when you need to cast I always suggest you do this explicitly to show others, or perhaps yourself in the future, that you intended for this behavior.
By the way, the gcc warning for this is -Wconversion. Unfortunately -Wall and -Wextra still leave alot of good warnings off.
Here are the flags I use when I want gcc to be very lint-like
-pedantic -std=c99 -ggdb3 -O0 -Wall -Wextra -Wformat=2 -Wmissing-include-dirs -Winit-self -Wswitch-default -Wswitch-enum -Wunused-parameter -Wfloat-equal -Wundef -Wshadow -Wlarger-than-1000 -Wunsafe-loop-optimizations -Wbad-function-cast -Wcast-qual -Wcast-align -Wconversion -Wlogical-op -Waggregate-return -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wpacked -Wpadded -Wredundant-decls -Wnested-externs -Wunreachable-code -Winline -Winvalid-pch -Wvolatile-register-var -Wstrict-aliasing=2 -Wstrict-overflow=2 -Wtraditional-conversion -Wwrite-strings
I also check my code first with cppcheck which is a free static code analyzer for C and C++. Highly recommended.
My simple guideline - if it needs a cast, it's probably wrong. If you don't need a cast, don't use them.
The reason you don't cast the return value of malloc is because you are always assigning the return value to a pointer type, and the C standard allows a void * to be implicitly cast to any other pointer type. Explicitly casting it is redundant, and therefore unnecessary.
You can't ask about casting in 'C' w/o understanding that casting covers more than one type of operation. There are essentially two, type conversion and type coercion. In C++, because it has more type info, it's creating 4 types of casts and codified this with an exclusive notation. reinterpret_cast<>, const_cast<>, dynamic_cast<> and static_cast<>. You don't have these in C since all casts have the syntax (ctype) but the reasons for them remain and it helps to understand why casting is required even though your question was about 'C' specifically.
The "need" for static cast is what you show in your example. The compiler will do them for you, even if you don't specify it - however, crank the warning level up high enough, and the compiler will warn you if there is a loss of precision as there is going from double to float (your return bar; statement). Adding a cast tells the compiler the loss of precision was intended.
The second least dangerous cast is a const cast<>. It's used to removed const or volatile from a type. This commonly occurs where structures have internal "caches". So a caller may have a const version of your structure, but an "internal function" needs to update the cache so will have to cast from a pointer to a const struct to a regular struct to update an internal field.
The most dangerous type is a reinterpret cast and why people will go on and on about how bad it is to cast. That's where you're not converting anything, but telling the compiler to reinterpret a value as a totally different type. What is below might have been added by a naive programmer trying to get rid of a compiler error.
char **ptostr = (char **p) "this is not a good idea";
Likely the correct fix was to use an '&' and this is how casting gets a bad reputation. Casts like this can be used for good or evil. I used it in the answer to another question about how to find the smallest power of 2 in order to leverage the power of the FPU in a CPU. A better example of being used for good, is when implementing linked lists. If the links live in the objects themselves, you have to cast from the link pointer back out to the enclosed object (a good use for the offsetof macro if the links can't be at the top of the structure).
A dynamic cast has no language support in C but the circumstance still occurs. If you have a heterogeneous list, then you might verify an object was of a given type using a field in the list's link header. Implemented manually, you would verify the type as being compatible and return NULL if it wasn't. This is special version of the reinterpret cast.
There are many sophisticated programing patterns that require casting so I wouldn't say casting needs to be avoided or indicates something is wrong. The problem with 'C' is how you write the unsafe ones in the same exact way as the safe ones. Keeping it contained and limited is a good practice so you can make sure you have it right (e.g., use library routines, strong typing and asserts if you can).
Casting a result should only done when strictly necessary; if you are using code developed from two different people (such as static libraries, or dynamic libraries), and two functions don't use compatible values, then casting is the only solution (as long as you don't try to cast a string to an integer).
Before to use the casting, it would be better to verify if the datatypes used are correct. In the example code (which has the purpose of providing an example), it doesn't make sense to declare the returned value to be a float value when the function returns a double.
double bar = foo();
What happens here is called promotional conversion, where the value of the casted variable is reserved after the conversion. The reverse is not true, i.e. float -> double. The only answer is to cast only when you really need to. Casting a lot is a sign of bad design.
In your example there's a loss of precision, but the cast is implicit. There are times when casting is absolutely necessary, such as when you're reading data from a byte stream or when all you have is data coming in through a void* pointer, but you know what data it represents. But for most part, casting should be avoided and reserved for these extreme cases.
What you're looking at is implicit type conversion. This is considered safe if you're starting with a type having a more restricted range than the one you're ending up with, i.e. short to int is OK, as is float to double.
I'm quite surprised that gcc isn't generating a warning when converting a double to a float; I believe Microsoft's compiler does.
You might find these two SO posts informative:
Specifically, what’s dangerous about casting the result of malloc?
Do Implict Function Declarations in C Actually Generate Object Code?
The admonition against casting the result of malloc() is a special case, due to C implicitly typing the result of previously undeclared functions to int (which IINM is disallowed as of C99).
Generally, you want to limit the use of explicit casts as much as possible; the only time you need to use one is if you're trying to assign a value of one type to a variable of an incompatible type (e.g., assign a pointer value to an int variable or vice versa). Since void * is compatible with every other pointer type, no explicit cast is needed. However, if you're trying to assign a value of type int * to a variable of type struct foo *, an explicit cast is required. If you find yourself assigning values of incompatible types a lot, then you may want to revisit your design.
Basically you need to cast arguments to functions that expect a different parameter than their prototype claims.
For example, isalpha() has a prototype with an int argument, but really expects an unsigned char.
char *p;
if ((*p != EOF) && isalpha((unsigned char)*p) /* cast needed */
{
/* ... */
}
And, you need to be extra careful with functions that accept a variable number of arguments, eg:
long big;
printf("%d\n", (int)big);
Edit
The compiler cannot convert the arguments of variadic functions to the proper type, because there is no type information available in the prototype itself. Consider a printf()-like function
int my_printf(const char *fmt, ...);
As far as the compiler is aware, you can pass values of all kinds of types in the "..." argument, and you must make sure the arguments match what the function expects. For example, let's say the my_printf() function accepts a value of type time_t with a corresponding "%t" specifier in the format string.
my_printf("UNIX Epoch: %t.\n", 0); /* here, 0 is an int value */
my_printf("UNIX Epoch: %t.\n", (time_t)0); /* and here it is a time_t */
My compiler does not want to make this fail! Apparently it (and the one at codepad too) passes 8 bytes for each argument in "..."
Using a prototype without "..." ( int my_printf(const char *fmt, time_t data); ), the compiler would automagically convert the first 0 to the right type.
Note: some compilers (gcc included) will validate the arguments against the format string for printf() if the format string is a literal string
There are at least two kinds of casts:
Casts of numeric values that cause a change of representation. (This is a term of art you will find in Harbison and Steele's very helpful C Reference Manual.) These casts are mostly innocuous; the only way you can do harm is by, e.g., casting a wider type to a narrower type, in which case you are deliberately throwing away bits. Only you, the programmer, know whether it's safe to throw away those bits.
C also has an insidious feature that it may perform a change of representation on your behalf when you assign, return, or pass a numeric expression whose type doesn't exactly match the type of the associate lvalue, result, or argument. I think this feature is pernicious, but it is firmly embedded in the C way of doing things. The gcc option -Wconversion will let you know where the compiler is doing a change of representation on your behalf, without being asked.
Casts that don't involve a change of representation but simply ask the compiler to view bits a certain way. These include casts between signed and unsigned types of the same size, as well as casts between pointer types that point to different sorts of data. The type void * enjoys a special status in C as the compiler will convert freely between void * and other data pointer types without a cast. Note that a cast between pointers of two different types of data never involves a change of representation. This is one reason the void * convention can work.
One reason C programmers try to avoid gratuitous casts is that when you write a cast, the compiler trusts you completely. If you make a mistake, the compiler is not going to catch it for you. For this reason I advise my student never to cast pointer types unless they know exactly what they are doing.
P.S. I thought it would be possible to write a short, helpful answer to this question. Wrong!