GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::malloc - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. cstdlib
  3. malloc

最終更新日時: 2026年08月05日 21時54分00秒 (JST)
rotarymars が更新

履歴 編集

function
<cstdlib>

std::malloc

namespace std {
  void *malloc( size_t size );
}

概要

sizeバイトの初期化されていないメモリ領域を確保する。

確保可能なら、配列の初めのポインタを返す。

確保不可能なら、nullを返す。

確保するサイズが 0 の時にmallocが返す値は、定義されていない。

具体的には、nullポインタが返される場合もある。

また、null以外のポインタが返された場合もあり、この場合はメモリリークを避けるため参照を解除せずにfree関数に渡すべきである。

この関数でできた、オブジェクトの寿命は、メモリ割り当て時から、 freeなどで解放されるまでである。

備考

この関数はスレッドセーフである。

メモリリークを避けるため、この関数で確保したメモリは、freeなどを使い、メモリ解放するべきである。

例

cppref より引用。

#include <cstdio>
#include <cstdlib>

int main()
{
  int *p1 = static_cast<int*>(std::malloc(4 * sizeof(int))); // 4個のint型配列のメモリ領域を確保
  int *p2 = static_cast<int*>(std::malloc(sizeof(int[4])));  // 上と同じ。
  int *p3 = static_cast<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)
      std::printf("p1[%d] == %d\n", n, p1[n]);
  }

  std::free(p1); // メモリを解放
  std::free(p2);
  std::free(p3);
}

出力例

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

関連項目

  • free: 確保したメモリを解放する。

参照

  • C N2310: 7.22.3 Memory management functions
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.