# std::malloc

From cppreference.com
< cpp‎ | memory‎ | c

Defined in header `<cstdlib>` |  |
void* malloc( std::size_t size ); |  |

Allocates `size` bytes of uninitialized storage.

If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any scalar type.

If `size` is zero, the behavior is implementation defined (null pointer may be returned, or some non-null pointer may be returned that may not be used to access storage, but has to be passed to std::free)

The following functions are required to be thread-safe:

- The library versions of `operator new` and `operator delete`
- User replacement versions of global `operator new` and `operator delete`
- std::calloc, std::malloc, std::realloc, std::aligned_alloc (since C++17)

Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call happens-before the next allocation (if any) in this order.

(since C++11)

### Parameters

size | - | number of bytes to allocate

### Return value

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

On failure, returns a null pointer.

### 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.

### Example

Run this code

    #include <iostream>
    #include <cstdlib>

    int main()
    {
        int* p1 = (int*)std::malloc(4*sizeof(int));  // allocates enough for an array of 4 int
        int* p2 = (int*)std::malloc(sizeof(int[4])); // same, naming the type directly
        int* p3 = (int*)std::malloc(4*sizeof *p3);   // same, without repeating the type name

        if(p1) {
            for(int n=0; n<4; ++n) // populate the array
                p1[n] = n*n;
            for(int n=0; n<4; ++n) // print it back out
                std::cout << "p1[" << n << "] == " << p1[n] << '\n';
        }

        std::free(p1);
        std::free(p2);
        std::free(p3);
    }

Output:

    p1[0] == 0
    p1[1] == 1
    p1[2] == 4
    p1[3] == 9

### See also

operator new operator new[] | allocation functions (function)
get_temporary_buffer (deprecated in C++17) | obtains uninitialized storage (function template)
C documentation for malloc

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/memory/c/malloc&oldid=90061"