{"id":3856,"date":"2022-08-20T20:17:23","date_gmt":"2022-08-20T14:47:23","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/"},"modified":"2022-08-20T20:17:23","modified_gmt":"2022-08-20T14:47:23","slug":"solved-do-i-cast-the-result-of-malloc","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/","title":{"rendered":"(Solved) Do I cast the result of malloc?"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-605858\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"605858\" data-parentid=\"605845\" data-score=\"2448\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<h3>TL;DR<\/h3>\n<pre><code>int *sieve = (int *) malloc(sizeof(int) * length);\n<\/code><\/pre>\n<p>has two problems. The cast and that you&#8217;re using the type instead of variable as argument for sizeof. Instead, do like this:<\/p>\n<pre><code>int *sieve = malloc(sizeof *sieve * length);\n<\/code><\/pre>\n<h3>Long version<\/h3>\n<p><strong>No<\/strong>; you <em>don&#8217;t<\/em> cast the result, since:<\/p>\n<ul>\n<li>It is unnecessary, as <code>void *<\/code> is automatically and safely promoted to any other pointer type in this case.<\/li>\n<li>It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).<\/li>\n<li>It makes you repeat yourself, which is generally bad.<\/li>\n<li>It can hide an error if you forgot to include <code>&lt;stdlib.h&gt;<\/code>. This can cause crashes (or, worse, <em>not<\/em> 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&#8217;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&#8217;s no automatic assumption that undeclared functions return <code>int<\/code>.<\/li>\n<\/ul>\n<p>As a clarification, note that I said &#8220;you don&#8217;t cast&#8221;, not &#8220;you don&#8217;t <em>need<\/em> to cast&#8221;. In my opinion, it&#8217;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&#8217;t know about the risks.<\/p>\n<p>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.<\/p>\n<p>To add further, your code needlessly repeats the type information (<code>int<\/code>) which can cause errors. It&#8217;s better to de-reference the pointer being used to store the return value, to &#8220;lock&#8221; the two together:<\/p>\n<pre><code>int *sieve = malloc(length * sizeof *sieve);\n<\/code><\/pre>\n<p>This also moves the <code>length<\/code> to the front for increased visibility, and drops the redundant parentheses with <code>sizeof<\/code>; they <em>are only needed<\/em> when the argument is a type name. Many people seem to not know (or ignore) this, which makes their code more verbose. Remember: <code>sizeof<\/code> is not a function! \ud83d\ude42<\/p>\n<hr>\n<p>While moving <code>length<\/code> to the front <em>may<\/em> 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:<\/p>\n<pre><code>int *sieve = malloc(sizeof *sieve * length);\n<\/code><\/pre>\n<p>Since keeping the <code>sizeof<\/code> first, in this case, ensures multiplication is done with at least <code>size_t<\/code> math.<\/p>\n<p>Compare: <code>malloc(sizeof *sieve * length * width)<\/code> vs. <code>malloc(length * width * sizeof *sieve)<\/code> the second may overflow the <code>length * width<\/code> when <code>width<\/code> and <code>length<\/code> are smaller types than <code>size_t<\/code>.<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">52<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Do I cast the result of malloc? <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] TL;DR int *sieve = (int *) malloc(sizeof(int) * length); has two problems. The cast and that you&#8217;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&#8217;t cast the result, since: It is unnecessary, as void * is &#8230; <a title=\"(Solved) Do I cast the result of malloc?\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/\" aria-label=\"More on (Solved) Do I cast the result of malloc?\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[324,387,386],"class_list":["post-3856","post","type-post","status-publish","format-standard","hentry","category-solved","tag-c","tag-casting","tag-malloc"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>(Solved) Do I cast the result of malloc? - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"(Solved) Do I cast the result of malloc? - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] TL;DR int *sieve = (int *) malloc(sizeof(int) * length); has two problems. The cast and that you&#8217;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&#8217;t cast the result, since: It is unnecessary, as void * is ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-08-20T14:47:23+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"(Solved) Do I cast the result of malloc?\",\"datePublished\":\"2022-08-20T14:47:23+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/\"},\"wordCount\":410,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"c++\",\"casting\",\"malloc\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/\",\"name\":\"(Solved) Do I cast the result of malloc? - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-08-20T14:47:23+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"(Solved) Do I cast the result of malloc?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"(Solved) Do I cast the result of malloc? - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/","og_locale":"en_US","og_type":"article","og_title":"(Solved) Do I cast the result of malloc? - JassWeb","og_description":"[ad_1] TL;DR int *sieve = (int *) malloc(sizeof(int) * length); has two problems. The cast and that you&#8217;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&#8217;t cast the result, since: It is unnecessary, as void * is ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/","og_site_name":"JassWeb","article_published_time":"2022-08-20T14:47:23+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"(Solved) Do I cast the result of malloc?","datePublished":"2022-08-20T14:47:23+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/"},"wordCount":410,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["c++","casting","malloc"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/","url":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/","name":"(Solved) Do I cast the result of malloc? - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-08-20T14:47:23+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-do-i-cast-the-result-of-malloc\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"(Solved) Do I cast the result of malloc?"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/3856","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=3856"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/3856\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=3856"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=3856"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=3856"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}