更新了文件名。开始了数据结构
This commit is contained in:
115
Chapter09/动态内存管理.md
Normal file
115
Chapter09/动态内存管理.md
Normal file
@@ -0,0 +1,115 @@
|
||||
# 目录
|
||||
- [目录](#目录)
|
||||
- [动态内存管理](#动态内存管理)
|
||||
- [函数传参相关问题](#函数传参相关问题)
|
||||
- [关于 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);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user