C語言中內存管理(函數)(malloc、free、calloc、realloc)

在這裏插入圖片描述
在這裏插入圖片描述

實例:

// c_memory_test.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *p_str1, *p_str2;								// 定義兩個char*指針

    /* 使用malloc()函數分配內存 */
     p_str1 = (char*)malloc(32);
     if (NULL==p_str1) {								// 檢查內存分配是否成功
         printf("Alloc p_str1 memory ERROR!\n");
         return -1;
     }   
 
     /* 使用calloc()函數分配內存 */
     p_str2 = (char*)calloc(32, sizeof(char));
     if (NULL==p_str2) {								// 檢查內存是否分配成功
         printf("Alloc p_str2 memory ERROR!\n");
         free(p_str1);									// 注意,這裏需要釋放p_str1佔用的內存
         return -1;
     }   
 
     strcpy(p_str1, "This is a simple sentence.");				// p_str1寫入一個字符串
     strcpy(p_str2, p_str1);								// p_str2寫入與p_str1相同的字符串
 
     /* 打印p_str1的結果 */
     printf("p_str1 by malloc():\n");
     printf("p_str1 address: 0x%.8x\n", p_str1);				// p_str1的內存地址
     printf("p_str1: %s(%d chars)\n", p_str1, strlen(p_str1));		// p_str1的內容
 
     /* 打印p_str2的結果 */
     printf("p_str2 by calloc():\n");
     printf("p_str2 address: 0x%.8x\n", p_str2);				// p_str2的內存地址
     printf("p_str2: %s(%d chars)\n", p_str2, strlen(p_str2));		// p_str2的內容
 
     /* 爲p_str1重新分配內存(減小) */
     p_str1 = (char*)realloc(p_str1, 16);
     if (NULL==p_str1) {								// 檢查內存分配結果
         printf("Realloc p_str1 memory ERROR!\n");
         free(p_str2);									// 注意,需要釋放p_str2佔用的內存
         return -1;
     }   
     p_str1[15] = '\0';									// 寫字符串結束符
 
     /* 爲p_str2重新分配內存(增大) */
     p_str2 = (char*)realloc(p_str2, 128);
     if (NULL==p_str2) {								// 檢查內存分配結果
         printf("Realloc p_str2 memory ERROR!\n");
         free(p_str1);									// 注意,需要釋放p_str1佔用的內存
         return -1;
     }   
     strcat(p_str2, "The second sentence in extra memory after realloced!");
 
     /* 打印p_str1的結果 */
     printf("p_str1 after realloced\n");
     printf("p_str1 address: 0x%.8x\n", p_str1);				// p_str1的內存地址
     printf("p_str1: %s(%d chars)\n", p_str1, strlen(p_str1));		// p_str1的內容
 
     /* 打印p_str2的結果 */
     printf("p_str2 after realloced:\n");
     printf("p_str2 address: 0x%.8x\n", p_str2);				// p_str2的內存地址
     printf("p_str2: %s(%d chars)\n", p_str2, strlen(p_str2));		// p_str2的內容
 
     /* 注意,最後要釋放佔用的內存 */
     free(p_str1);										// 釋放p_str1佔用的內存
     free(p_str2);										// 釋放p_str2佔用的內存
 
     return 0;
 }

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

發佈了119 篇原創文章 · 獲贊 25 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章