The short answer
In C++ code you rarely need malloc. Reach for std::vector, std::string, or a smart pointer first. Use malloc when a C library requires it, because the library returns memory you must release yourself, or when you are writing low-level code that manages raw memory on purpose. Whichever you use, every allocation needs exactly one matching release.
What malloc does
malloc asks the heap for a block of raw bytes and returns a pointer to it. You give it a size in bytes, and it returns a void*, or a null pointer if the request fails. It doesn’t know what type you will store, and it doesn’t run constructors. You release the block with free.
Using malloc in C++
C++ doesn’t convert a void* to another pointer type on its own, so the result needs a cast. The size is in bytes, so five ints need count * sizeof(int):
// malloc_demo.cpp
#include <cstddef>
#include <cstdlib>
#include <iostream>
int main() {
std::size_t count = 5;
int* numbers = static_cast<int*>(std::malloc(count * sizeof(int)));
if (numbers == nullptr) {
std::cerr << "allocation failed\n";
return 1;
}
numbers[0] = 42;
std::cout << numbers[0] << '\n';
std::free(numbers); // pair malloc with free, not delete
return 0;
}
std::malloc and std::free come from <cstdlib>. The null check matters because malloc can fail.
Where malloc still belongs
Some C functions return memory that you own and must release with free. On POSIX systems, two common examples are strdup, which copies a string into new memory, and getline, which allocates its buffer for you. Calling delete on that memory is a bug, even when the code appears to work.
If you write low-level code that manages raw memory on purpose, realloc resizes a block you already own, and calloc returns zeroed memory. Both still pair with free.
Where malloc is the wrong tool
- Class types.
mallocdoesn’t call constructors, andfreedoesn’t call destructors. For objects with real constructors, usenewor a container instead. - Ordinary arrays.
std::vectorhandles sizing, copying, and freeing for you. - Mixed release. Calling
deleteon malloc’d memory, orfreeon memory fromnew, is undefined behavior.
Here is the mix-up in code:
int* value = static_cast<int*>(std::malloc(sizeof(int)));
delete value; // wrong: this memory came from malloc, so release it with free
How Valgrind reports malloc mistakes
If you never call free, Valgrind reports the block as definitely lost, the same way it reports a leaked new. If you call delete on malloc’d memory, Valgrind reports:
Mismatched free() / delete / delete []
To run Valgrind on a program like this, follow how to use valgrind in c.
Quick rule
- Use
std::vector,std::string, andstd::unique_ptrby default. - Use
malloconly where a C API requires it, and release the memory withfree. - Never mix
mallocwithdelete, ornewwithfree.