目录
  • 前言:
  • C 语言为内存的分配和管理提供了几个函数:
  • 1.malloc() 用法
  • 2.calloc() 用法
  • 3.realloc() 与 free() 用法

前言:

简单记录一下,内存管理函数

为什么使用动态内存呢?

简单理解就是可以最大限度调用内存

用多少生成多少,不用时就释放而静止内存不能释放

动态可避免运行大程序导致内存溢出


C 语言为内存的分配和管理提供了几个函数:

头文件:<stdlib.h>

C语言动态内存管理介绍

注意:void * 类型表示未确定类型的指针 

1.malloc() 用法

 分配一块大小为 num 的内存空间

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main() {
    char name[12];
    char *test;
 
    strcpy(name, "KiKiNiNi");
 
    // 动态分配内存
    test = (char *) malloc(26 * sizeof(char));
 
    // (void *) malloc(int num) -> num = 26 * sizeof(char)
    // void * 表示 未确定类型的指针
    // 分配了一块内存空间 大小为 num 存放值是未知的
 
    if (test == NULL) {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    } else {
        strcpy(test, "Maybe just like that!");
    }
 
    printf("Name = %s\n", name);
    printf("Test: %s\n", test);
 
    return 0;
}
 
// 运行结果
// Name = KiKiNiNi
// Test: Maybe just like that!

2.calloc() 用法

 分配 num 个长度为 size 的连续空间

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main() {
    char name[12];
    char *test;
 
    strcpy(name, "KiKiNiNi");
 
    // 动态分配内存
    test = (void *) calloc(26, sizeof(char));
 
    // (void *) calloc(int num, int size) -> num = 26 / size = sizeof(char)
    // void * 表示 未确定类型的指针
    // 分配了 num 个 大小为 size 的连续空间 存放值初始化为 0
 
    if (test == NULL) {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    } else {
        strcpy(test, "Maybe just like that!");
    }
 
    printf("Name = %s\n", name);
    printf("Test: %s\n", test);
 
    return 0;
}
 
// 运行结果
// Name = KiKiNiNi
// Test: Maybe just like that!

3.realloc() 与 free() 用法

重新调整内存的大小和释放内存

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main() {
    char name[12];
    char *test;
 
    strcpy(name, "KiKiNiNi");
 
    // 动态分配内存
    test = (char *) malloc(26 * sizeof(char));
 
    // (void *) malloc(int num) -> num = 26 * sizeof(char)
    // void * 表示 未确定类型的指针
    // 分配了一块内存空间 大小为 num 存放值是未知的
 
    if (test == NULL) {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    } else {
        strcpy(test, "Maybe just like that!");
    }
 
    /* 假设您想要存储更大的描述信息 */
    test = (char *) realloc(test, 100 * sizeof(char));
    if (test == NULL) {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    } else {
        strcat(test, " It's a habit to love her.");
    }
 
    printf("Name = %s\n", name);
    printf("Test: %s\n", test);
 
    // 释放 test 内存空间
    free(test);
 
    return 0;
}
 
// 运行结果
// Name = KiKiNiNi
// Test: Maybe just like that! It's a habit to love her.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。