Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

malloc
c++
memory
allocation

What is malloc in C++?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
}

RELATED TAGS

malloc
c++
memory
allocation
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring