文章目录
一、动态内存函数的介绍
1.1 malloc函数
使用:
void* malloc(size_t size)
这个函数向内存申请一块连续可用的空间,并返回指向这块空间的指针。
- 如果开辟成功,则返回一个指向开辟好空间的指针。
- 如果开辟失败,则返回一个NULL指针,因此malloc的返回值一定要做检查。
- 返回值的类型是 void* ,所以malloc函数并不知道开辟空间的类型,具体在使用的时候使用者自己来决定。
- 如果参数 size 为0,malloc的行为是标准是未定义的,取决于编译器。
1.2 calloc函数
void* calloc (size_t num, size_t size);
- 函数的功能是为 num 个大小为 size 的元素开辟一块空间,并且把空间的每个字节初始化为0。
- 与函数 malloc 的区别只在于 calloc 会在返回地址之前把申请的空间的每个字节初始化为全0。
1.3 realloc函数
void* realloc (void* ptr, size_t size);
- ptr 是要调整的内存地址
- size 调整之后新大小
- 返回值为调整之后的内存起始位置。
- 这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到 新 的空间。
realloc函数使用有两个注意情况
1.原有的空间足够大,直接在后面追加内存即可,数据不发生变化。
2.原有的空间不够大,在堆区找一个满足题意大小的空间。返回新空间的地址,并把数据拷到空间上。
1.4 free函数
C语言提供了另外一个函数free,专门是用来做动态内存的释放和回收的,函数原型如下:
void free (void* ptr)
- 如果参数 ptr 指向的空间不是动态开辟的,那free函数的行为是未定义的。
- 如果参数 ptr 是NULL指针,则函数什么事都不做。
二、常见的动态内存错误
2.1 对空指针NULL解引用操作
#include <stdio.h>
int main()
{
int* p = (int*)malloc(40);
*p = 20;
return 0;//如果malloc is fail,则对p进行解引用就会报错。
}
2.2 对动态内存开辟的空间越界访问
#include <stdio.h>
int main()
{
int* p = (int*)calloc(10, 4);
if (p == NULL)
{
printf("calloc is fail\n");
exit(-1);
}
int i = 0;
for (i = 0; i <= 10; i++)
{
*(p + i) = i;//当i=10时,存在越界访问。
}
free(p);
p = NULL;
return 0;
}
2.3 对非动态开辟内存进行free操作
#include <stdio.h>
int main()
{
int a = 10;
int* p = &a;
free(p);//对非动态开辟的内存进行free操作
p = NULL;
return 0;
}
2.4 使用free释放一块动态开辟内存的一部分
#include <stdio.h>
int main()
{
int* p = (int*)malloc(100);
p++;
free(p);//p不再指向动态内存的起始位置
return 0;
}
2.5 对同一块动态内存多次释放
#include <stdio.h>
int main()
{
int* p = (int*)malloc(100);
free(p);
free(p);//重复释放
return 0;
}
2.6 对动态内存开辟的空间忘记释放
void test()
{
int* p = (int*)malloc(100);
if (NULL != p)
{
*p = 20;
}
}
int main()
{
test();//如果对动态内存开辟的空间不释放,程序如果一直不停的话,容易造成内存泄漏。
while (1);
}
三、几道经典笔试题
题目一、
void GetMemory(char* p)
{
p = (char*)malloc(100);//1 动态开辟空间没有释放
}
void Test(void)
{
char* str = NULL;
GetMemory(str);//传值调用后,str=NULL;
strcpy(str, "hello world");2 对空指针进行字符串拷贝
printf(str);
}
题目二、
char* GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory();//str所指向的空间在函数调用后已经释放
printf(str);
}
题目三、
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);//动态开辟的开辟的空间没有释放
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
题目四、
void Test(void)
{
char* str = (char*)malloc(100);//假设开辟成功
strcpy(str, "hello");
free(str);
if (str != NULL)
{
strcpy(str, "world");//在空间已经返回给操作系统后,任然对这部分空间进行操作
printf(str);
}
}