std::malloc

Header: <cstdlib>

Allocates size bytes of uninitialized storage.

# Declarations

void* malloc( std::size_t size );

# Parameters

# Return value

On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with std::free() or std::realloc().

# Notes

This function does not call constructors or initialize memory in any way. There are no ready-to-use smart pointers that could guarantee that the matching deallocation function is called. The preferred method of memory allocation in C++ is using RAII-ready functions std::make_unique, std::make_shared, container constructors, etc, and, in low-level library code, new-expression.

For loading a large file, file mapping via OS-specific functions, e.g. mmap on POSIX or CreateFileMapping(A/W) along with MapViewOfFile on Windows, is preferable to allocating a buffer for file reading.

# Example

#include <cstdlib> 
#include <iostream>   
#include <memory>
#include <string>
 
int main() 
{
    constexpr std::size_t size = 4;
    if (auto ptr = reinterpret_cast<std::string*>(std::malloc(size * sizeof(std::string))))
    {
        try
        {
            for (std::size_t i = 0; i < size; ++i)
                std::construct_at(ptr + i, 5, 'a' + i);
            for (std::size_t i = 0; i < size; ++i)
                std::cout << "ptr[" << i << "] == " << ptr[i] << '\n';
            std::destroy_n(ptr, size);
        }
        catch (...) {}
        std::free(ptr);
    }
}

# See also