Trusted answers to developer questions

What is malloc in C++?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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().

Press + to interact
#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);
}
}

RELATED TAGS

malloc
c++
memory
allocation
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?