Last active
August 29, 2015 14:17
-
-
Save hiroshiro/be77263899ada73c14dc to your computer and use it in GitHub Desktop.
malloc free関数のtest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* MemoryAlloc01.c */ | |
/* 動的に配列的なデータ域を確保する。 */ | |
#include <stdio.h> | |
#include <stdlib.h> | |
int main(void) | |
{ | |
int *piData; | |
printf("int *piData; piDataのポインタ : %p\n", piData); //定義前のポインタの値を表示 | |
piData = NULL; //確保したメモリエリアのポインタを格納する変数と定義 | |
printf("piData = NULL; piDataのポインタ : %p\n", piData); //NULL定義直後のポインタの値を表示 | |
piData = malloc(sizeof(int)); // int 型データのサイズ分メモリを確保 | |
if (piData == NULL) { | |
printf("piData == NULL\n"); | |
return -1; // 何もせず終了 | |
} | |
printf("piData = malloc(sizeof(int));確保直後のpiDataポインタ : %p\n", piData); // 確保直後のポインタを表示 | |
*piData = 500; // 確保したエリアの中に500を代入 | |
printf("*piData = 500; *piDataの値 : %d\n", *piData); // 500を代入直後の値を表示 | |
printf("メモリエリアを解放前の*piDataの値 : %d\n", *piData); | |
printf("メモリエリアを解放前のpiDataのポインタ : %p\n", piData); | |
free(piData); //メモリエリアを解放 | |
printf("free(piData); メモリエリアを解放後の*piDataの値 : %d\n", *piData); | |
printf("メモリエリアを解放後のpiDataのポインタ : %p\n", piData); | |
piData = NULL;// 再びNULL | |
printf("piData = NULL; 解放後再びNULL *piDataの値 : %d\n", *piData); | |
printf("解放後NULLのpiDataのポインタ : %p\n", piData); | |
return 0; | |
} | |
/* 実行結果 */ | |
/* int *piData; piDataのポインタ : 0x7fff57c6f640 */ | |
/* piData = NULL; piDataのポインタ : 0x0 */ | |
/* piData = malloc(sizeof(int));確保直後のpiDataポインタ : 0x7ffe6a4049c0 */ | |
/* *piData = 500; *piDataの値 : 500 */ | |
/* メモリエリアを解放前の*piDataの値 : 500 */ | |
/* メモリエリアを解放前のpiDataのポインタ : 0x7ffe6a4049c0 */ | |
/* free(piData); メモリエリアを解放後の*piDataの値 : 500 */ | |
/* メモリエリアを解放後のpiDataのポインタ : 0x7ffe6a4049c0 */ | |
/* コマンドを中断しました */ | |
// 再びNULLを入れるとコマンドを中断するようになる。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment