CC++C++17Learn C++

What C Programming Is Used For Memory Allocations?

What C Programming Is Used For Memory Allocations

Memory usage is really important in C and C++ programming. In the C language malloc, calloc, realloc functions comes from the <alloc.h> header and C++ language allows you to use malloc in C++ also calloc and realloc too. These memory allocations are fairly old and mostly used in C and require great caution if you use them in C++. In modern C++ we should use modern ways of C++ like std::vector, std::array, std::template, lambdas, iterators, etc. In addition we can use std::unique_ptr (since C++11) and other smart pointers with class members too.

In programming, all data and operations during runtime are stored in the memory of our computers, including IoT or other microdevices. This memory is generally a RAM (Random Access Memory) that 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 this post, we explain how to use memory in C and C++, how to allocate something in memory and manage memory dynamically, what memory methods or functions are used for Dynamic Memory Management, how to use malloc() and free(), and what Static Memory Allocation is. What exactly is Dynamic Memory Allocation? What is the difference between Static Memory Allocation and Dynamic Memory Allocation?

Let’s learn how to use two types of memory allocations in programming: static memory allocation and dynamic memory allocation, as well as how to compile C++ in Windows. It will help you to easily build C++ applications.

What C programming function is used for memory allocations?

What does static memory allocation mean?

Static Memory Allocation is a memory allocation method that is defined by variable definitions when programming and it has a fixed size that can not be changed at run-time. These variables are defined in our programs using items like constants, strings, pointers, arrays, and record 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.

Because 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 data arrays than required which ultimately 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. Using pointers, 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 new and delete operations are higher level memory management operations which are a better choice than these ones.

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

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> 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 malloc() and free() functions.

What C programming is used for memory allocations – malloc() function?

In C and C++ programming, malloc() function is a Dynamic Memory Allocation function that allocates a block of size bytes from the memory heap. It allows a program to allocate memory explicitly as it is needed, and in the exact amounts needed. The allocation is from the main memory. The heap is used for dynamic allocation of variable-sized blocks of memory. Many data structures, for example, trees and lists, naturally employ heap memory allocation. In the large data models, all the space beyond the program stack to the end of available memory is available for the heap.

Here is the syntax for malloc function:

The malloc function returns a pointer to the newly allocated block of memory if it is successful. If there is no space exists for the new block, it returns NULL. The contents of the block are left unchanged. If the argument size == 0, malloc returns NULL.

For example we can allocate char array as below,

How can I use malloc() and free() functions?

The 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.


Is there a full C example of using the C and C++ malloc() and free() functions?

Here is a full C++ example about to use malloc() and free() functions

C++ also allows you to use malloc command. Here is a C++ example about how to use malloc.

Note that malloc() is faster than calloc() function because it doesn’t initialize all bytes in the allocated storage to zero. Be sure that you filled with correct data before you output or operate with your dynamic data.

In C++ programming, some developers do not use std::vector, even allocators. Some developers may need to use dynamically sized array, std::array is used for this purpose, and some developers get their arrays from other function or code that is known to return an array; rewritten codes as a vector form or something may require a lot of time. Thus, unique_ptr can be used in those kind of memory allocation methods. In modern C++, we should can use std::unique_ptr (Since C++11) and other smart pointers when we need to, when other ways of programming is not work or you may need to code as fast as possible. It’s a tool of last resort.

These malloc, calloc, realloc memory allocation functions are very old and mostly used in C applications (i.e. in IoT programming) and these functions may require very professional approaches in C++ programming. In modern C++ we should use modern ways of C++ like std::vector, std::array, std::template, lambdas, iterators, etc. in addition we can use std::unique_ptr (Since C++11) and other smart pointers with class members too. Memory usage is really important in C and C++ programming.

Although the free C++ Builder Community Edition is extremely powerful it is intended for students, beginners, and startups. If you are a regular business or do not qualify for the free community edition then you can download a free trial of the very latest full RAD Studio C++ Builder version.

C++ Builder is the easiest and fastest C and C++ IDE for building everything from simple to professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.

There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise versions of C++ Builder and there is a trial version you can download from here.

Download RAD Studio 11 Now

See What’s New in RAD Studio 11

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

Dr. Yilmaz Yoru has 35+ years of coding with more than 30+ programming languages, mostly C++ on Windows, Android, Mac-OS, iOS, Linux, and some other operating systems. He graduated and received his MSc and PhD degrees from the Department of Mechanical Engineering of Eskisehir Osmangazi University. He is the founder and CEO of ESENJA LLC Company. His interests are Programming, Thermodynamics, Fluid Mechanics, Artificial Intelligence, 2D & 3D Designs, and high-end innovations.
Related posts
C++C++11C++14Learn C++Syntax

How To Convert u32string To A wstring In C++

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

How To Learn The Move Constructors In Modern C++?

C++C++17Code SnippetLearn C++

How To Convert Char Array String To Unicode String Correctly In C++?

Artificial Intelligence TechC++Language FeatureLearn C++

How To Develop A Simple Hopfield Network In C++