{"id":3153,"date":"2024-05-10T11:38:35","date_gmt":"2024-05-10T11:38:35","guid":{"rendered":"https:\/\/www.skillvertex.com\/blog\/?p=3153"},"modified":"2024-05-10T11:38:35","modified_gmt":"2024-05-10T11:38:35","slug":"difference-between-malloc-and-calloc-with-examples","status":"publish","type":"post","link":"https:\/\/www.skillvertex.com\/blog\/difference-between-malloc-and-calloc-with-examples\/","title":{"rendered":"Difference Between malloc() and calloc() with Examples"},"content":{"rendered":"\n<div class=\"wp-block-rank-math-toc-block\" id=\"rank-math-toc\" id=\"rank-math-toc\"><p>Table of Contents<\/p><nav><ul><li ><a href=\"#difference-between-malloc-and-calloc-with-examples\">Difference Between malloc() and calloc() with Examples<\/a><\/li><li ><a href=\"#initialization\">Initialization<\/a><\/li><li ><a href=\"#return-value\">Return Value<\/a><\/li><li ><a href=\"#difference-between-malloc-and-calloc-in-c\">Difference between malloc() and calloc() in C<\/a><\/li><li ><a href=\"#faq-difference-between-malloc-and-calloc-with-examples\">FAQ- Difference Between malloc() and calloc() with Examples<\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"difference-between-malloc-and-calloc-with-examples\">Difference Between malloc() and calloc() with Examples<\/h2>\n\n\n\n<p>The two functions such as malloc () and calloc() are library functions that can allocate dynamically. Dynamic refers to the memory that is allocated during the run time(execution of the program) from the heap segment.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"initialization\">Initialization<\/h2>\n\n\n\n<p>malloc() will allocate a memory block of the provided size(in bytes) and then it can return a pointer to the beginning of the block. Malloc() won&#8217;t initialize the memory. Whereas, if you attempt to read from the allocated memory without even initializing it, then it can show undefined behavior. This meant the value that you read will be garbage values.<\/p>\n\n\n\n<p>The <code>calloc()<\/code> function in C and C++ is used to allocate memory for an array of elements and initializes all the bytes in the allocated memory to zero. It takes two arguments: the number of elements to allocate memory for and the size of each element in bytes. <code>calloc()<\/code> then returns a pointer to the allocated memory block.<\/p>\n\n\n\n<p>Because <code>calloc()<\/code> initializes all the bytes to zero, if you try to read the values from the allocated memory without explicitly assigning values to them, you will indeed get 0 or equivalent representations for the data type you are using. This behavior is different from the <code>malloc()<\/code> function, which allocates memory but does not initialize it, so the values in the memory block may contain arbitrary data.<\/p>\n\n\n\n<p><strong>Parameters<\/strong><\/p>\n\n\n\n<p>The malloc() function in C and C++ takes a single argument, which is the number of bytes to allocate. It returns a pointer to a block of memory that is large enough to store the specified number of bytes. <code>malloc()<\/code> does not initialize the memory it allocates, which means the contents of the allocated memory are undefined, and you need to explicitly initialize it if needed.<\/p>\n\n\n\n<p>calloc() indeed takes two arguments:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The number of blocks or elements to be allocated.<\/li>\n\n\n\n<li>The size of each block or element in bytes.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"return-value\">Return Value<\/h2>\n\n\n\n<p>Both malloc() and calloc() return a pointer to the allocated memory block on successful allocation. If the allocation fails for any reason, they return a <code>NULL<\/code> pointer to indicate failure. It&#8217;s important to check the returned pointer to ensure that the allocation was successful before attempting to use the allocated memory.<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C code that demonstrates the difference\n\/\/ between calloc and malloc\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n \nint main()\n{\n    \/\/ Both of these allocate the same number of bytes,\n    \/\/ which is the amount of bytes that is required to\n    \/\/ store 5 int values.\n \n    \/\/ The memory allocated by calloc will be\n    \/\/ zero-initialized, but the memory allocated with\n    \/\/ malloc will be uninitialized so reading it would be\n    \/\/ undefined behavior.\n    int* allocated_with_malloc = malloc(5 * sizeof(int));\n    int* allocated_with_calloc = calloc(5, sizeof(int));\n \n    \/\/ As you can see, all of the values are initialized to\n    \/\/ zero.\n    printf(\"Values of allocated_with_calloc: \");\n    for (size_t i = 0; i &lt; 5; ++i) {\n        printf(\"%d \", allocated_with_calloc&#91;i]);\n    }\n    putchar('\\n');\n\n    \/\/ This malloc requests 1 terabyte of dynamic memory,\n    \/\/ which is unavailable in this case, and so the\n    \/\/ allocation fails and returns NULL.\n    int* failed_malloc = malloc(1000000000000);\n    if (failed_malloc == NULL) {\n        printf(\"The allocation failed, the value of \"\n               \"failed_malloc is: %p\",\n               (void*)failed_malloc);\n    }\n \n    \/\/ Remember to always free dynamically allocated memory.\n    free(allocated_with_malloc);\n    free(allocated_with_calloc);\n}\n<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Values of allocated_with_calloc: 0 0 0 0 0 \nThe allocation failed, the value of failed_malloc is: (nil)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"difference-between-malloc-and-calloc-in-c\">Difference between malloc() and calloc() in C<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>malloc()<\/strong><\/td><td><strong>calloc()<\/strong><\/td><\/tr><tr><td>Malloc() refers to a function which can create one block of memory of a fixed size<\/td><td>Calloc() is a function that will assign a specified number of blocks of memory to single variable<\/td><\/tr><tr><td>It can only take one segment.<\/td><td>It will take only two segments.<\/td><\/tr><tr><td>Malloc() will be faster than calloc ().<\/td><td>calloc () is comparatively  slower than mall0c()<\/td><\/tr><tr><td>It has more time efficiency<\/td><td>calloc() will have very low time efficiency.<\/td><\/tr><tr><td>Syntax: void*<br>malloc(size_t size;<\/td><td>Syntax : void* calloc(size_t num, size_t size);<\/td><\/tr><tr><td>It won&#8217;t initialize the memory to zero.<\/td><td>It will  initialize the memory to zero<\/td><\/tr><tr><td>It won&#8217;t add any extra memory overhead<\/td><td>calloc() will add extra memory overhead.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq-difference-between-malloc-and-calloc-with-examples\">FAQ- Difference Between malloc() and calloc() with Examples<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1698661702133\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q1. What is the return type of malloc () or calloc ()?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. malloc() and calloc() will return\u00a0<strong>void *<\/strong><\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1698661707314\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q2. What is the syntax of malloc?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. <strong>ptr = (int*) malloc(100 * sizeof(int));<\/strong><br \/>It allocates memory for 100 integers, and since the size of an <code>int<\/code> is typically 4 bytes on many systems, this will allocate 400 bytes of memory. The pointer <code>ptr<\/code> holds the address of the first byte in the allocated memory, which is the starting address of the block of 400 bytes.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1698661715067\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q3. What is difference between malloc and new?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. <code>new<\/code> is a C++ operator for dynamic memory allocation, initializing objects and returning the exact data type.<br \/><code>malloc()<\/code> is a C and C++ library function for general memory allocation, not initializing objects, and returning <code>void*<\/code><\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Difference Between malloc() and calloc() with Examples The two functions such as malloc () and calloc() are library functions that can allocate dynamically. Dynamic refers to the memory that is allocated during the run time(execution of the program) from the heap segment. Initialization malloc() will allocate a memory block of the provided size(in bytes) and &#8230; <a title=\"Difference Between malloc() and calloc() with Examples\" class=\"read-more\" href=\"https:\/\/www.skillvertex.com\/blog\/difference-between-malloc-and-calloc-with-examples\/\" aria-label=\"More on Difference Between malloc() and calloc() with Examples\">Read more<\/a><\/p>\n","protected":false},"author":4,"featured_media":3171,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27],"tags":[523],"class_list":["post-3153","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-difference-between-malloc-and-calloc-with-examples","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-33"],"_links":{"self":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3153","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/comments?post=3153"}],"version-history":[{"count":11,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3153\/revisions"}],"predecessor-version":[{"id":10748,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3153\/revisions\/10748"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media\/3171"}],"wp:attachment":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media?parent=3153"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/categories?post=3153"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/tags?post=3153"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}