跳转至

动态内存管理

  • 四个涉及到的函数:malloc calloc free realloc 参考文档

  • 原则:谁申请,谁释放。对于申请的内存,是申请使用该内存的权限。free后是free了你的权限,地址中的内容如何改变是未知的。

  • void* 和 函数指针 之间的转换在c99中是未定义的,与其他类型的指针都可以互相转换。

  • free后,该地址的指针应当习惯性重新设置为NULL

    #include <stdio.h>
    #include <stdlib.h>
    #include <malloc.h>
    
    #define N 3
    
    int main(void)
    {
    
        int* p = malloc(sizeof(int));
        if (p == NULL)
        {
            printf("malloc() error!\n");
            exit(1);
        }
    
        *p = 10;
        printf("%p -> %d\n", p, *p);
    
        free(p);
        p = NULL;   // 重新赋值为NULL
    
        return 0;
    }
    

typedef

  • 为已有的数据类型改名 格式:[ typedef 已有的数据类型 新名字; ]

  • typedef 和 宏定义 的去区别。

    #define IP int*
    IP p, q;
    // p 被理解为 int* p;
    // q 被理解为 int q;
    
    
    typedef int* IP;
    // p 被理解为 int* p;
    // q 被理解为 int* q
    

  • typedef 示例

    typedef int ARR[6];
    ARR a;      // int a[6];
    
    struct node_st
    {
        int i;
        float f;
    };
    typedef struct node_st NODE;
    NODE a;     // struct node_st a;
    
    typedef struct
    {
        int i;
        float f; 
    } NODE, *NODEP;
    
    typedef int FUNC(int);
    FUNC f;     // int f(int);
    
    typedef int* FUNCP(int);
    FUNCP p;    // int* p(int);
    
    typedef int*(*FUNCP)(int);
    FUNCP p;    // int*(*p)(int);