C++C++11C++14C++17Introduction to C++Learn C++

How To Use calloc() Function In Your C And C++ Programs

How can we use memory in C and C++? How can I allocate something in memory? How can I manage memory dynamically? What kind of memory methods or functions are used for the Dynamic Memory Management? How can I use free()? How can I use calloc()?

In computers, all data and operations during runtime is stored in the memory of our computers, IoTs, or in other microdevices. This memory is generally RAM (Random Access Memory). RAM allows data items to be read or written in almost the same amount of time irrespective of the physical location of data inside the memory.

In general, In programming, there are two kinds of memory allocations, Static Memory Allocation, and Dynamic Memory Allocation.

What does dynamic memory allocation mean?

Static Memory Allocation is a memory allocation method that is defined by variable definitions when programming. It has a fixed size and cannot be changed at run-time. These variables are items like constants, strings, pointers, arrays, and structures. When a program is compiled, the compiler allocates part of the memory to store data. This is called Static Memory Allocation or Compile-time Memory. There are limitations in such static memory allocation to use these kinds of variables.

What kind of limitations are there on C/C++ static memory allocations?

These allocations are done in memory exclusively allocated to a program. We can’t increase the size of static allocations to handle more new elements. Thus, this may result in declaring larger arrays than really required which means a waste of memory usage. If we used less data than expected, Static Memory Allocations don’t allow us to reduce array size to save memory. It is hard to create advanced dynamic data structures which can be deleted, reallocated variables, linked lists, trees, and other data, which are essential in most real-life programming situations.

What does dynamic memory allocation mean?

Dynamic Memory Allocation is a memory allocation method in which the memory is allocated during the execution of a program (at run-time). Dynamic Memory Management functions/methods involve the use of pointers and standard library functions. Sometimes we use pointers to point to the address of blocks of memory which is allocated dynamically. So we can easily access or operate on those dynamic memory allocations.

Note that malloc, calloc, realloc functions comes from C language included in the <alloc.h> and it can be used with C++ included in the <cstdlib> library. These functions might be very dangerous in Modern C++ thus using the “new” and “delete” operations are recommended for higher level memory management operations than malloc, calloc and realloc.

Here is the Comparison Table of new and delete methods with malloc and free methods in C++,

Memory Management FeatureUsing new and delete methodsUsing malloc and free methods
Memory allocated fromfree storeheap
Use of constructor / destructorYesNo
ReturnsFully typed pointervoid* pointer
On failurenever returns NULL, ThrowsReturns NULL
Memory size requiredCalculated by compilerMust be specified in bytes
Handling arraysHas an explicit versionRequires manual calculations
ReallocatingNot handled intuitivelySimple (no copy constructor)
Call of reverseImplementation definedNo
Low memory casesCan add a new memory allocatorNot handled by user code
OverridableYesNo

The C++ language is a great programming language with its ancestor C programming language. C programming language has both Static Memory Allocation and Dynamic Memory Allocation methods. Most used Dynamic Memory Allocation functions are defined in header <stdlib.h> and <cstdlib> libraries, mostly we use malloc(), calloc(), realloc() and free().

FunctionSyntax Description
mallocvoid* malloc( size_t size );allocates a block of from memory heap and returns a pointer
callocvoid* calloc( size_t num, size_t size );allocates a block of from memory heap, initializes it to zero and returns a pointer
reallocvoid* realloc( void *ptr, size_t new_size );re-allocates the size of the allocated memory block,copies the contents to a new location
freevoid free( void* ptr );Free block of memory blk allocated from memory heap

Let’s see how we use calloc() and free() functions.

How do you use the calloc() function?

calloc() function is a Dynamic Memory Allocation function that allocates memory for an array of elements and initializes all bytes in the allocated storage to zero. calloc provides access to the C memory heap. The heap is available for dynamic allocation of variable-sized blocks of memory. Many data structures, such as trees and lists, naturally employ heap memory allocation. calloc allocates a block of size nitems * size. The block is initialized to 0. calloc returns a pointer to the newly allocated block. If not enough space exists for the new block or if nitems or size is 0, calloc returns NULL.

In the large data models, all the space beyond the program stack to the end of available memory is available for the heap.

Syntax:

For example we can allocate char array as below,

How do you use calloc() and free() functions?

free() function is a Dynamic Memory Allocation function that frees allocated block. free() deallocates a memory block allocated by a previous call to callocmalloc, or realloc.

Syntax:

Here is a full C and C++ example about calloc() function

What about a full C++ example of using the calloc() function?

Note that calloc is slower than malloc because of time needed to fill memory allocation zero. Do not use if you don’t need to zero the allocation.

Where can I read more about C / C++ memory management?

You can click the following dynamic search link to view other articles on this blog about C and C++ memory management: https://learncplusplus.org/?s=memory+allocation


Did you know you can download a free trial of C+ Builder? Go to this link to try it out now.

close

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.

About author

33+ years of coding with more than 30+ programming languages, mostly C++ on Windows, Android, Mac-OS, iOS, Linux and some other operating systems. Dr. Yilmaz Yoru was born in 1974, Eskisehir-Turkey. He graduated from the department of Mechanical Engineering of Eskisehir Osmangazi University in 1997. One year later he started to work in the same university as an assistant. He received his MSc and PhD degrees from the same department of the same university. He has married and he is a father of a son. Some of his interests are Programming, Thermodynamics, Fluid Mechanics and Artificial Intelligence. He also likes the graphical 2D & 3D design and high-end innovations.
Related posts
C++ComponentsDatabaseIntroduction to C++Language FeatureLearn C++

Get To Know The Powerful C++ Data Bindings In Windows Apps

C++Introduction to C++Language FeatureLearn C++

How to Create a New Windows FMX Static Library In C++

C++C++11C++14C++17Introduction to C++Learn C++

How To Use C++ front() And back() Methods Of Vectors

C++Generic ProgrammingIntroduction to C++Language FeatureLearn C++

5 Things You Need To Know About Optimization In C++ Builder

fr_FRFrench