What is malloc in C++?

malloc is a function that allocates a block of bytes in memory and then returns a pointer to the beginning of the block. This block’s content is not initialized. In the world of programming, where every space counts, there are numerous instances when we only want an array to have a specific amount of space at runtime. That is, we want to create an array that dynamically occupies a particular amount of space. We do this using malloc.

Code

The following code runs the malloc function that does not call constructors or initialize memory in any way. To avoid a memory leak, the returned pointer must be deallocated with std::free() or std::realloc().

#include <iostream>
#include <cstdlib>
#include <string>
int main()
{
// allocates enough for an array of 4 strings
if(auto p = (std::string*)std::malloc(4 * sizeof(std::string)))
{
int i = 0;
try
{
for(; i != 4; ++i) // populate the array
new(p + i) std::string(5, 'a' + i);
for(int j = 0; j != 4; ++j) // print it back out
std::cout << "p[" << j << "] == " << p[j] << '\n';
}
catch(...) {}
using std::string;
for(; i != 0; --i) // clean up
p[i - 1].~string();
std::free(p);
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved