malloc関数 - メモリの動的確保
malloc関数を使用するとメモリを動的に確保できます。「stdlib.h」を読み込む必要があります。
#include <stdlib.h> void *malloc(size_t size);
malloc関数はヒープ領域にメモリを確保します。
第一引数は、割り当てるサイズをバイト単位で指定します。型はsize_t型です。size_t型は、環境によって、幅が異なりますが、16bit以上の符号なし整数とC言語仕様で定義されています。現代的な環境であれば、0~符号あり32bit整数型の最大値の範囲(0~2147483647)で、値を指定すれば安心だと想定します。(例外的な環境があれば、プリーズテルミー)。
戻り値は、確保されたメモリ領域の先頭のアドレスです。戻り値の型は、汎用ポインタ型「void*」です。どんなポインタ型にも代入できます。
malloc関数で割り当てられたメモリは、初期化されていないことに注意しましょう。
一般的なアプリケーションやライブラリで動的メモリ確保する場合は、0初期化されるcalloc関数をお勧めしています。
mallocで確保したメモリ領域は、使い終わったら、free関数を使って解放しましょう。解放し忘れるとメモリリークになります。
malloc関数のサンプル
malloc関数のサンプルを書いてみます。
配列の動的な生成
配列を動的に生成するサンプルです。
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// int32_tのサイズで、10の長さのメモリ領域を確保(4バイト*10=40バイト)
int32_t nums_length = 10;
int32_t* nums = malloc(sizeof(int32_t) * nums_length);
// 配列の操作
nums[0] = 10;
printf("%d\n", nums[0]);
// 解放
free(nums);
}
構造体データの動的な生成
構造体のデータを動的に生成するサンプルです。
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
// 書籍情報を表現する構造体の定義
struct myapp_book {
int32_t id;
const char* name;
int32_t price;
};
int main(void) {
// 構造体の動的メモリ確保(malloc)
struct myapp_book* book = malloc(sizeof(struct myapp_book));
book->id = 1;
book->name = "C99 Book";
book->price = 2000;
printf("id: %d, name: %s, price: %d\n", book->id, book->name, book->price);
// メモリ解放
free(book);
}
構造体の配列の動的な生成
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
// 書籍情報を表現する構造体の定義
struct myapp_book {
int32_t id;
const char* name;
int32_t price;
};
int main(void) {
// 構造体の配列を動的メモリ確保
int32_t books_length = 10;
struct myapp_book* books = malloc(sizeof(struct myapp_book) * books_length);
books[0].id = 1;
books[0].name = "C99 Book";
books[0].price = 2000;
printf("books[0] id: %d, name: %s, price: %d\n", books[0].id, books[0].name, books[0].price);
// メモリ解放
free(books);
}
C言語ゼミ


