Ought to I formed the consequence of malloc (successful C)?

Ought to I formed the consequence of malloc (successful C)?

Successful this motion, person instructed successful a remark that I ought to not formed the consequence of malloc. i.e., I ought to bash this:

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

instead than:

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

Wherefore would this beryllium the lawsuit?


Nary; you shouldn’t formed the consequence, since:

  • It is pointless, arsenic void * is routinely and safely promoted to immoderate another pointer kind successful this lawsuit.
  • It provides muddle to the codification, casts are not precise casual to publication (particularly if the pointer kind is agelong).
  • It makes you repetition your self, which is mostly atrocious.
  • It tin fell an mistake if you forgot to see <stdlib.h>. This tin origin crashes (oregon, worse, not origin a clang till manner future successful any wholly antithetic portion of the codification). See what occurs if pointers and integers are otherwise sized; past you're hiding a informing by casting and mightiness suffer bits of your returned code. Line: arsenic of C99 implicit capabilities are gone from C, and this component is nary longer applicable since location's nary automated presumption that undeclared capabilities instrument int.

Arsenic a clarification, line that I mentioned “you shouldn’t formed”, not “you don't demand to formed”. Successful my sentiment, it's a blunder to see the formed, equal if you received it correct. Location are merely nary advantages to doing it, however a clump of possible dangers, and together with the formed signifies that you don't cognize astir the dangers.

Besides line, arsenic commentators component retired, that the supra talks astir consecutive C, not C++. I precise firmly accept successful C and C++ arsenic abstracted languages.


To adhd additional, your codification needlessly repeats the kind accusation (int) which tin origin errors. It's amended to de-mention the pointer being utilized to shop the instrument worth, to "fastener" the 2 unneurotic:

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

Any whitethorn opportunity: “Fine, antecedently the kind was repeated, and present the adaptable sanction is repeated; isn’t this conscionable arsenic repetitive arsenic earlier? However is that immoderate amended?” The quality is that if you 1 time alteration the kind of the adaptable and bury to alteration the kind nether the sizeof to lucifer, you volition silently acquire an allocation of the incorrect dimension and nary informing astir it; however if you alteration the sanction of the adaptable, however bury to alteration the sanction nether sizeof to lucifer, it is much possible that the aged sanction nary longer resolves to thing, truthful your codification volition halt compiling, prompting you to hole the error.

This besides strikes the length to the advance for accrued visibility, and drops the redundant parentheses with sizeof; they are lone wanted once the statement is a kind sanction. Galore group look to not cognize (oregon disregard) this, which makes their codification much verbose. Retrieve: sizeof is not a relation! :)

Piece shifting length to the advance whitethorn addition visibility successful any uncommon circumstances, 1 ought to besides wage attraction that successful the broad lawsuit, it ought to beryllium amended to compose the look arsenic:

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

Since preserving the sizeof archetypal, successful this lawsuit, ensures multiplication is completed with astatine slightest size_t mathematics.

Comparison: malloc(sizeof *sieve * length * width) vs. malloc(length * width * sizeof *sieve) the 2nd whitethorn overflow the length * width once width and length are smaller varieties than size_t.


Successful C, you don't demand to formed the instrument worth of malloc. The pointer to void returned by malloc is automagically transformed to the accurate kind. Nevertheless, if you privation your codification to compile with a C++ compiler, a formed is wanted. A most popular alternate amongst the assemblage is to usage the pursuing:

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

which moreover frees you from having to concern astir altering the correct-manus broadside of the look if always you alteration the kind of sieve.

Casts are atrocious, arsenic group person pointed retired. Particularly pointer casts.


Once running with C, dynamic representation allocation through malloc is a cornerstone of galore purposes. Deciding whether or not to formed the consequence of malloc is a determination that has sparked argument amongst C programmers for years. Piece it was frequently thought of essential successful older C requirements, contemporary C requirements supply a nuanced position. Knowing the causes down casting oregon not casting the instrument worth of malloc is important for penning cleanable, moveable, and maintainable C codification. This article explores the arguments, requirements, and champion practices surrounding this subject to supply a blanket usher for C builders.

Is Specific Kind Casting Essential for malloc successful C?

Traditionally, successful older variations of C (earlier C99), it was mostly beneficial to formed the instrument worth of malloc. This was due to the fact that malloc returned a void, which is a generic pointer kind. Earlier the C99 modular, implicit conversions from void to another pointer sorts have been not allowed. Frankincense, casting was required to delegate the consequence of malloc to a pointer of a circumstantial kind, specified arsenic int oregon char. Nevertheless, the C99 modular launched implicit conversions from void to immoderate another entity pointer kind, making the formed technically pointless successful about instances. This alteration importantly altered the scenery of C programming practices, starring to ongoing discussions astir whether or not the formed ought to inactive beryllium utilized.

What are the Benefits of Omitting the Formed?

Omitting the formed once utilizing malloc successful contemporary C presents respective benefits. Archetypal, it reduces codification muddle and improves readability. Cleaner codification is mostly simpler to realize and keep. 2nd, and possibly much importantly, omitting the formed tin aid observe possible errors. If you bury to see , the compiler volition implicitly presume that malloc returns an int. Assigning this int to a pointer with out a formed volition make a informing oregon an mistake, alerting you to the lacking see. Once you formed, you suppress these warnings, possibly masking a overmuch deeper job successful your codification, associated to lacking see information. So, by letting the compiler execute an implicit conversion from void, you return vantage of the compiler's kind checking capabilities.

Nevertheless bash I get the hash for the existent perpetrate palmy Git?

Causes to Debar Casting the Consequence of malloc

Avoiding specific casting presents respective benefits, making it a most popular kind successful modern C programming. 1 important vantage is improved codification maintainability. Once the kind of the pointer modifications, you lone demand to replace the pointer declaration; you don't demand to modify all case wherever malloc is utilized with that pointer. This reduces the hazard of errors and makes refactoring simpler. Furthermore, omitting the formed makes the codification cleaner and much readable, aligning with contemporary coding requirements that stress readability and simplicity. By avoiding pointless casts, builders tin compose much sturdy and maintainable C purposes. Different facet is that specific casts tin generally fell delicate errors and brand debugging much hard.

See the pursuing illustration:

 include <stdio.h> include <stdlib.h> int main() { int ptr = malloc(10  sizeof(int)); // No cast needed if (ptr == NULL) { perror("malloc failed"); return 1; } for (int i = 0; i < 10; i++) { ptr[i] = i; printf("%d ", ptr[i]); } printf("\n"); free(ptr); return 0; } 

Successful this codification, nary specific formed is utilized, ensuing successful cleaner and much simple codification.

Present's a examination successful a array:

Characteristic With Formed With out Formed
Readability Somewhat much verbose Cleaner and much concise
Mistake Detection Whitethorn fell lacking see warnings Helps observe lacking see
Maintainability Requires updates if pointer kind modifications Nary modifications wanted if pointer kind modifications
Portability Essential successful pre-C99 Modular-compliant successful C99 and future
"Simplicity is the eventual sophistication." - Leonardo da Vinci

Successful decision, piece casting the consequence of malloc was a communal pattern successful older C requirements, contemporary C requirements (C99 and future) brand it pointless. Omitting the formed leads to cleaner, much maintainable, and possibly safer codification by leveraging the compiler's kind checking capabilities. By adhering to these requirements, builders tin compose sturdy and readable C purposes. If you're inactive explicitly casting, you whitethorn privation to re-measure that pattern based mostly connected these concerns. For additional speechmaking connected C representation direction, mention to this tutorial. Beryllium certain to cheque retired this mention connected malloc. Don't bury to analyze this GNU documentation arsenic fine.


Ingo Schwarze: Forget reusability, aim for perfection -- BSDCan 2018

Ingo Schwarze: Forget reusability, aim for perfection -- BSDCan 2018 from Youtube.com

Previous Post Next Post

Formulario de contacto