How to allocate memory for an array using malloc() & calloc()?
This is for you if...
Preparing for C++ Interview
C developers started learning C++
Passionate C++ developers looking for multiple options, instead of saying why malloc, calloc??? where we can use new & delete.
malloc, calloc & realloc are C library functions used for dynamic memory allocation(management), defined in stdlib.h/cstdlib header.
We can allocate memory for the array as follows...
malloc(sizeof(int) NO_OF_ELEMENTS)
calloc(sizeof(int), NO_OF_ELEMENTS)
Both functions return a generic pointer(void*). So we need to typecast it in C++ code, as C++ is a strongly type-checked language.
We should use **free()* to free the allocated memory in the heap otherwise there will be a memory leak**.
Code Example:
#include <iostream>
// #include <cstdlib>
void demo_malloc() {
std::cout << "Malloc Demo...\n";
constexpr size_t NO_OF_ELEMENTS{10};
int* p = (int*)malloc(sizeof(int) * NO_OF_ELEMENTS);
// Insert elements
for( int i = 0; i < NO_OF_ELEMENTS; ++i) {
p[i] = i + 1;
}
// Print
for( int i = 0; i < NO_OF_ELEMENTS; ++i) {
std::cout << p[i] << " ";
}
free(p);
p = nullptr;
std::cout << '\n';
}
void demo_calloc() {
std::cout << "Calloc Demo...\n";
constexpr size_t NO_OF_ELEMENTS{10};
int* p = (int*)calloc(sizeof(int), NO_OF_ELEMENTS);
// Insert elements
for( int i = 0; i < NO_OF_ELEMENTS; ++i) {
p[i] = i + 1;
}
// Print
for( int i = 0; i < NO_OF_ELEMENTS; ++i) {
std::cout << p[i] << " ";
}
free(p);
p = nullptr;
}
int main() {
demo_malloc();
demo_calloc();
return 0;
}
Notes:
double free() is dangerous. Once free() is called, the pointer may point to an invalid memory location. So the next free() call may lead to undefined behaviour.
Use a debugger to verify this.
Be cautious. After calling free(), we should set the pointer to nullptr. While some compilers may do this automatically, it's best not to rely on it. Practice safe programming.
ASSIGNMENT:
Try double free() and see the runtime error.(Don't initialize pointer to nullptr, othwise you can't see it). Write your learning points in the comment section.
Want to take your C++ skills to the next level? Visit cppforme.com for resources, tips, and expert advice to help you improve your coding techniques and become a better developer. And if you need additional help or support, feel free to contact me by visiting my site.