std::malloc
STD::malloc
Defined in header | | |
---|---|---|
void* malloc( std::size_t size | | |
分配size
未初始化存储的字节。
如果分配成功,则返回一个指针,指向分配的内存块中的最低%281%29字节,该指针适合于任何标量类型。
如果size
为零,行为为实现定义的%28空指针可能会被返回,或者一些非空指针可能不会被用来访问存储,但必须传递给std::free
29%。
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) |
---|
- 的库版本
operator new
和operator delete
- 全局用户替换版本
operator new
和operator delete
std::calloc
,,,std::malloc
,,,std::realloc
,,,std::aligned_alloc
%28自C++17%29
对分配或释放特定存储单元的这些函数的调用是以单个总顺序进行的,并且每个这样的释放调用都会发生。发生-之前下一次按此顺序分配%28(如果有%29)。
%28自C++11%29
参数
size | - | number of bytes to allocate |
---|
返回值
成功后,返回指向新分配内存开始的指针。返回的指针必须用std::free()
或std::realloc()
...
失败时,返回一个空指针。
注记
此函数不以任何方式调用构造函数或初始化内存。没有现成的智能指针可以保证调用匹配的去分配函数。C++中内存分配的首选方法是使用Raii就绪函数。std::make_unique
,,,std::make_shared
、容器构造函数等,以及在低级库代码中,新表达式...
例
二次
#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
}
二次
产出:
二次
p1[0] == 0
p1[1] == 1
p1[2] == 4
p1[3] == 9
二次
另见
operator newoperator new[] | allocation functions (function) |
---|---|
get_temporary_buffer (deprecated in C++17) | obtains uninitialized storage (function template) |
c.malloc文件
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。