std::malloc

定义于头文件 <cstdlib>
void* malloc( std::size_t size );

分配 size 字节的未初始化存储。

若分配成功,则返回指向分配的适合对任何标量类型对齐的内存块中,最低(首)字节的指针。

size 为零,则行为是实现定义的(可以返回空指针,或某个不可用于访问存储,但必须传递给 std::free 的非空指针)。

要求下列函数是线程安全的:

对这些分配或解分配特定存储单元的函数调用以单独全序出现,并且在此顺序中,每个解分配调用先发生于下个分配(若存在)。

(C++11 起)

目录

参数

size - 要分配的字节数

返回值

成功时,返回指向新分配内存起始的指针。返回的指针必须用 std::free()std::realloc() 解分配。

失败时,返回空指针。

注意

任何情况下,此函数不调用构造函数或初始化内存。无能保证调用匹配的解分配函数的预备使用的智能指针。 C++ 中偏好的内存分配方法是用 RAII 预备函数 std::make_uniquestd::make_shared 、容器构造函数等,而在低层代码中为 new 表达式

示例

#include <iostream>   
#include <cstdlib> 
 
int main() 
{
    int* p1 = (int*)std::malloc(4*sizeof(int));  // 为 4 个 int 的数组分配足够空间
    int* p2 = (int*)std::malloc(sizeof(int[4])); // 同上,直接命名
    int* p3 = (int*)std::malloc(4*sizeof *p3);   // 同上,无需重复类型名
 
    if(p1) {
        for(int n=0; n<4; ++n) // 填充数组
            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


参阅

分配函数
(函数)
(C++17 中弃用)
获得未初始化存储
(函数模板)
mallocC 文档

版本历史

  • (当前 | 先前 2017年8月29日 (二) 23:08Fruderica讨论 | 贡献. . (2,005字节) (-19). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 16:57P12bot讨论 | 贡献 . . (2,024字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:02P12bot讨论 | 贡献 . . (2,024字节) (-71). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 16:30P12bot讨论 | 贡献 . . (2,095字节) (+81). . (r2.7.3) (机器人添加:en, es, it, ru 去除:zh) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 03:25P12讨论 | 贡献 . . (2,014字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (2,014字节) (-56). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:09P12讨论 | 贡献 . . (2,070字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (2,070字节) (+937). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年5月4日 (五) 15:20P12bot讨论 | 贡献 . . (1,133字节) (+163). . (r2.7.3) (机器人添加:de, en, fr, ja, pl, pt) (撤销)
  • 当前 | 先前 2012年5月1日 (二) 03:37P12讨论 | 贡献 . . (970字节) (0). . (1个修订: Import from Dokuwiki) (撤销)
  • 当前 | 先前) 2012年5月1日 (二) 03:37P12讨论 | 贡献. . (970字节) (+970). . (Import from dokuwiki)