Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/memory/c/malloc"

From cppreference.com
< cpp‎ | memory‎ | c
m (wording)
m ({{c}}, ., fmt, ., headers sorted)
 
(17 intermediate revisions by 8 users not shown)
Line 1: Line 1:
 
{{cpp/title|malloc}}
 
{{cpp/title|malloc}}
 
{{cpp/memory/c/navbar}}
 
{{cpp/memory/c/navbar}}
{{ddcl | header=cstdlib |
+
{{ddcl|header=cstdlib|
 
void* malloc( std::size_t size );
 
void* malloc( std::size_t size );
 
}}
 
}}
  
Allocates {{tt|size}} bytes of uninitialized storage.
+
Allocates {{c|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 allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any scalar type (at least as strictly as {{lc|std::max_align_t}}) ([[cpp/language/object#Object creation|implicitly creating]] objects in the destination area).
  
If {{tt|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)
+
If {{c|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 {{lc|std::free}}).
 +
 
 +
{{cpp/memory/thread_safety_note}}
  
 
===Parameters===
 
===Parameters===
 
{{par begin}}
 
{{par begin}}
{{par | size | number of bytes to allocate }}
+
{{par|size|number of bytes to allocate}}
 
{{par end}}
 
{{par end}}
  
 
===Return value===
 
===Return value===
On success, returns the pointer to the beginning of newly allocated memory. The returned pointer must be deallocated with {{lc|std::free()}} or {{tt|std::realloc()}}.
+
On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with {{lc|std::free()}} or {{lc|std::realloc()}}.
  
 
On failure, returns a null pointer.
 
On failure, returns a null pointer.
Line 23: Line 25:
 
===Notes===
 
===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 {{lc|std::make_unique}}, {{lc|std::make_shared}}, container constructors, etc, and, in low-level library code, [[cpp/language/new|new-expression]].
 
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 {{lc|std::make_unique}}, {{lc|std::make_shared}}, container constructors, etc, and, in low-level library code, [[cpp/language/new|new-expression]].
 +
 +
For loading a large file, file mapping via OS-specific functions, e.g. [https://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html {{tt|mmap}}] on POSIX or {{tt|CreateFileMapping}}([https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfilemappinga {{tt|A}}]/[https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-createfilemappingw {{tt|W}}]) along with [https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile {{tt|MapViewOfFile}}] on Windows, is preferable to allocating a buffer for file reading.
  
 
===Example===
 
===Example===
 
{{example
 
{{example
| code=
+
|code=
#include <iostream> 
+
 
#include <cstdlib>  
 
#include <cstdlib>  
 +
#include <iostream> 
 +
#include <memory>
 +
#include <string>
  
 
int main()  
 
int main()  
 
{
 
{
     int* p1 = (int*)std::malloc(4*sizeof(int)); // allocates enough for an array of 4 int
+
     constexpr std::size_t size = 4;
     int* p2 = (int*)std::malloc(sizeof(int[4])); // same, naming the type directly
+
     if (auto ptr = reinterpret_cast<std::string*>(std::malloc(size * sizeof(std::string))))
    int* p3 = (int*)std::malloc(4*sizeof *p3);  // same, without repeating the type name
+
     {
 
+
         try
     if(p1) {
+
        {
         for(int n=0; n<4; ++n) // populate the array
+
            for (std::size_t i = 0; i < size; ++i)
            p1[n] = n*n;
+
                std::construct_at(ptr + i, 5, 'a' + i);
        for(int n=0; n<4; ++n) // print it back out
+
            for (std::size_t i = 0; i < size; ++i)
            std::cout << "p1[" << n << "] == " << p1[n] << '\n';
+
                std::cout << "ptr[" << i << "] == " << ptr[i] << '\n';
 +
            std::destroy_n(ptr, size);
 +
        }
 +
        catch (...) {}
 +
        std::free(ptr);
 
     }
 
     }
 
    std::free(p1);
 
    std::free(p2);
 
    std::free(p3);
 
 
}
 
}
| output=
+
|output=
p1[0] == 0
+
p[0] == aaaaa
p1[1] == 1
+
p[1] == bbbbb
p1[2] == 4
+
p[2] == ccccc
p1[3] == 9
+
p[3] == ddddd
 
}}
 
}}
 
  
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/memory/new/dsc operator_new}}
+
{{dsc inc|cpp/memory/new/dsc operator_new}}
{{dsc inc | cpp/memory/dsc get_temporary_buffer}}
+
{{dsc inc|cpp/memory/dsc get_temporary_buffer}}
{{dsc see c | c/memory/malloc}}
+
{{dsc see c|c/memory/malloc}}
 
{{dsc end}}
 
{{dsc end}}
  
[[de:cpp/memory/c/malloc]]
+
{{langlinks|de|es|fr|it|ja|pl|pt|ru|zh}}
[[es:cpp/memory/c/malloc]]
+
[[fr:cpp/memory/c/malloc]]
+
[[it:cpp/memory/c/malloc]]
+
[[ja:cpp/memory/c/malloc]]
+
[[pl:cpp/memory/c/malloc]]
+
[[pt:cpp/memory/c/malloc]]
+
[[ru:cpp/memory/c/malloc]]
+
[[zh:cpp/memory/c/malloc]]
+

Latest revision as of 11:23, 12 June 2023

 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
 
Dynamic memory management
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Allocators
Garbage collection support
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)



 
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 (at least as strictly as std::max_align_t) (implicitly creating objects in the destination area).

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:

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)

Contents

[edit] Parameters

size - number of bytes to allocate

[edit] 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().

On failure, returns a null pointer.

[edit] 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.

[edit] 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);
    }
}

Output:

p[0] == aaaaa
p[1] == bbbbb
p[2] == ccccc
p[3] == ddddd

[edit] See also

allocation functions
(function) [edit]
(deprecated in C++17)(removed in C++20)
obtains uninitialized storage
(function template) [edit]
C documentation for malloc