In all programs, not just in C 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 the C and C++ malloc function as well as the free
function.
You’ll learn how to use memory in C++ and C programming, 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?
By learning how to use these 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.
Table of Contents
What C programming is used for static memory operations?
Static Memory Allocation is a memory allocation method that is defined by variable definitions when programming and it has a fixed size that cannot 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.
Arrays are a good example of static memory. Here is a static memory array example composed with 500 integer numbers,
1 2 3 |
int array[500]; |
This example above, it reserves sizeof(int)
* 500 bytes of memory, which means it reserves 4*500 = 2000 bytes during the runtime of application, and it remains there.
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 C programming is used for dynamic memory operations?
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 Feature | Using new and delete methods | Using malloc and free methods |
---|---|---|
Memory allocated from | free store | heap |
Use of constructor / destructor | Yes | No |
Returns | Fully typed pointer | void* pointer |
On failure | never returns NULL , Throws | Returns NULL |
Memory size required | Calculated by compiler | Must be specified in bytes |
Handling arrays | Has an explicit version | Requires manual calculations |
Reallocating | Not handled intuitively | Simple (no copy constructor) |
Call of reverse | Implementation defined | No |
Low memory cases | Can add a new memory allocator | Not handled by user code |
Overridable | Yes | No |
The C++ language is a great programming language with its ancestry coming from the C programming language. The 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()
.
Function | Syntax | Description |
malloc | void* malloc( size_t size ); | allocates a block of from memory heap and returns a pointer |
calloc | void* calloc( size_t num, size_t size ); | allocates a block of from memory heap, initializes it to zero and returns a pointer |
realloc | void* realloc( void *ptr, size_t new_size ); | re-allocates the size of the allocated memory block,, copies the contents to a new location |
free | void free( void* ptr ); | Free block of memory blk allocated from memory heap |
Let’s see how we use malloc()
and free()
functions.
How is the C malloc() function used for memory operations?
The 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.
Syntax:
1 2 3 |
void* malloc( size_t size ); |
For example, we can allocate char array as below,
1 2 3 4 |
char *str; str = (char *) malloc(80); |
If successful, malloc returns a pointer to the newly allocated block of memory. If not enough 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.
What C programming is used for free() function memory operations?
The free()
function is a Dynamic Memory Allocation function that frees allocated block. Free()
deallocates a memory block allocated by a previous call to calloc
, malloc
, or realloc
.
Syntax:
1 2 3 |
void free( void* ptr ); |
For example, we can allocate a char array and free it as below,
1 2 3 4 5 6 7 |
char *str; str = (char *) malloc(80); // delete from the memory when done free(str); |
Is there a full C programming example of malloc – free memory operations?
Here is a full C programming example with malloc memory operations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <stdio.h> #include <string.h> #include <alloc.h> #include <process.h> int main(void) { char *str; printf("malloc() example:\n"); if ( str = (char *) malloc(255) ) // Dynamic Memory Allocation { strcpy(str, "LearnCPlusPlus.org"); printf("Dynamic Memory Allocated :%s Adress:%p\n\n", str, str); free(str); // Free str from the memory } else { printf("Not enough memory to allocate buffer\n"); exit(1); // Terminate program if out of memory } getchar(); return 0; } |
Is there a full C++ programming example of malloc – free function memory operations?
Here is a full C++ programming example with malloc memory operations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <cstdlib> int main() { char *str; if( str = (char *) malloc(255) ) // Allocate Memory { std::cout << "Dynamic Memory Allocated\n"; if(str = (char *) realloc(str, 50)) // Reallocate memory { std::cout << "Dynamic Memory is Reallocated\n"; } std::free(str); // Free memory } getchar(); return 0; } |
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 modern C++ we should use std::unique_ptr
(Since C++11) and other smart pointers.
Use RAD Studio C++ to supercharge your C++ development. Why not download a free trial today!
Design. Code. Compile. Deploy.
Start Free Trial
Free C++Builder Community Edition