1.8 KiB
1.8 KiB
目录
动态内存管理
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); // 重新分配空间
原则:谁申请谁释放。
函数传参相关问题
- 要么用二级指针
- 要么用返回值
#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,这样后续再操作这个指针,就会报段错误。
#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);
}