Files
Linux-C-Notes/C09-动态内存管理/C9-动态内存管理.md
2024-06-23 17:45:58 +08:00

105 lines
1.8 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 目录
- [目录](#目录)
- [动态内存管理](#动态内存管理)
- [函数传参相关问题](#函数传参相关问题)
- [关于 free](#关于-free)
# 动态内存管理
```` c
void *calloc(size_t nmemb, size_t size); // 分配n个size空间
void *malloc(size_t size); // 分配size空间
void free(void *ptr);
void *realloc(void *ptr, size_t size); // 重新分配空间
````
原则:谁申请谁释放。
## 函数传参相关问题
1. 要么用二级指针
2. 要么用返回值
```c
#include <stdio.h>
#include <stdlib.h>
// void func(int **p, int n)
// {
//     *p = malloc(n);
//     if (NULL == *p)
//         exit(1);
//     return;
// }
void *func(int *p, int n)
{
    p = malloc(n);
    if (NULL == p)
        exit(1);
    return p;
}
int main()
{
    int  num = 100;
    int *p   = NULL;
    // func(&p, num);
    p = func(p, num);
    free(p);
    exit(0);
}
```
## 关于 free
`free`操作没有扣掉那块内存,没有改变那块内存的值,也没有改变指针的指向。
仅仅是让这个指针不在有操作那块内存的权力,所以如果依旧用这个指针,可能不会报错,依旧可以操作那块内存。但是这就是野指针了,这是十分危险的。
比较好的习惯是在`free`之后马上给指针赋值`NULL`,这样后续再操作这个指针,就会报段错误。
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *p = NULL;
    p = malloc(sizeof(int));
    if (NULL == p)
    {
        printf("malloc() error!\n");
        exit(1);
    }
    *p = 10;
    printf("%p-->%d\n", *p);
    free(p);
    p = NULL;   // !important
    printf("%p-->%d\n", *p);
    // 0x5a677368 -- > 1516729192
    *p = 123;
    printf("%p-->%d\n", *p);
    // 0x7b -- > 0
    exit(0);
}
```