目录
动态内存管理
为什么存在动态内存分配
我们已经掌握的内存开辟方式有:
int val = 20; 在栈空间上开辟四个字节
char arr[10] = {0}; 在栈空间上开辟10个字节的连续空间
但是上述的开辟空间的方式有两个特点:
- 空间开辟大小是固定的。
- 数组在申明的时候,必须指定数组的长度,它所需要的内存在编译时分配。
但是对于空间的需求,不仅仅是上述的情况。有时候我们需要的空间大小在程序运行的时候才能知道,
那数组的编译时开辟空间的方式就不能满足了。
这时候就只能试试动态存开辟了。
动态内存函数的介绍
malloc
C语言提供了一个动态内存开辟的函数:
void* malloc (size_t size);
这个函数向内存申请一块连续可用的空间,并返回指向这块空间的指针。
- 如果开辟成功,则返回一个指向开辟好空间的指针。
- 如果开辟失败,则返回一个NULL指针,因此malloc的返回值一定要做检查。
- 返回值的类型是 void* ,所以malloc函数并不知道开辟空间的类型,具体在使用的时候使用者自己来决定。
- 如果参数 size 为0,malloc的行为是标准是未定义的,取决于编译器。
malloc的使用要配合free
malloc开辟的空间中的值是随机值,所以一般需要自己初始化
int main()
{
//张三
//申请
int* p = (int*)malloc(20);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
//使用
int i = 0;
for (i = 0; i < 5; i++)
{
p[i] = i + 1;
}
for (i = 0; i < 5; i++)
{
printf("%d ", p[i]);
}
/*for (i = 0; i < 5; i++)
{
*(p + i) = i + 1;
}
for (i = 0; i < 5; i++)
{
printf("%d ", *(p + i));
}*/
//释放
free(p);
p = NULL;
return 0;
}
free
C语言提供了另外一个函数free,专门是用来做动态内存的释放和回收的,函数原型如下:
void free (void* ptr);
free函数用来释放动态开辟的内存。
- 如果参数 ptr 指向的空间不是动态开辟的,那free函数的行为是未定义的。
- 如果参数 ptr 是NULL指针,则函数什么事都不做。
malloc和free都声明在 stdlib.h 头文件中。
free(ptr)把ptr指向的空间释放后,不能够把ptr置成空指针,所以为了防止以后野指针ptr被使用,最好自己把ptr置成空指针。
calloc
C语言还提供了一个函数叫 calloc , calloc 函数也用来动态内存分配。原型如下:
void* calloc (size_t num, size_t size);
- 函数的功能是为 num 个大小为 size 的元素开辟一块空间,并且把空间的每个字节初始化为0。
- 与函数 malloc 的区别只在于 calloc 会在返回地址之前把申请的空间的每个字节初始化为全0。
int main()
{
int* p = (int*)calloc(10, sizeof(int));
if (p == NULL)
{
printf("calloc()-->%s\n", strerror(errno));
return 1;
}
//使用
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", p[i]);
}
//释放
free(p);
p = NULL;
return 0;
}
malloc在返回前不会初始化,calloc在返回前会初始化,calloc效率就没有malloc高,根据需求使用。
realloc
- realloc函数的出现让动态内存管理更加灵活。
- 有时会我们发现过去申请的空间太小了,有时候我们又会觉得申请的空间过大了,那为了合理的使用内存,我们一定会对内存的大小做灵活的调整。那 realloc 函数就可以做到对动态开辟内存大小的调整。
函数原型如下:
void* realloc (void* ptr, size_t size);
- ptr 是要调整的内存地址
- size 调整之后新大小
- 返回值为调整之后的内存起始位置。
- 这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到 新 的空间。
- realloc在调整内存空间的是存在两种情况:
情况1:原有空间之后有足够大的空间
情况2:原有空间之后没有足够大的空间
情况1
当是情况1 的时候,要扩展内存就直接原有内存之后直接追加空间,原来空间的数据不发生变化。
情况2
当是情况2 的时候,原有空间之后没有足够多的空间时,扩展的方法是:在堆空间上另找一个合适大小的连续空间来使用。这样函数返回的是一个新的内存地址。
开辟失败返回NULL
由于上述的两种情况,realloc函数的使用就要注意一些
int main()
{
int* p = (int*)malloc(20);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
//使用
int i = 0;
for (i = 0; i < 5; i++)
{
p[i] = i + 1;
}
int* ptr = (int*)realloc(p, 400000);
if (ptr != NULL)
{
p = ptr;
//使用
for (i = 5; i < 10; i++)
{
p[i] = i + 1;
}
for (i = 0; i < 10; i++)
{
printf("%d ", p[i]);
}
}
//释放
free(p);
p = NULL;
return 0;
}
当reallc返回的不是NULL时才可以用p接收
补充:realloc也可以像malloc一样申请空间
//malloc
//calloc
//realloc - 调整申请的堆区内存的大小的
#include <stdio.h>
int main()
{
realloc(NULL, 20);//和 malloc(20)功能相同;
return 0;
}
常见的动态内存错误
1.对NULL指针的解引用操作
int main()
{
int* p = (int*)malloc(20);
//可能会出现对NULL指针的解引用操作
//所以malloc函数的返回值要判断的
int i = 0;
for (i = 0; i < 5; i++)
{
p[i] = i;
}
free(p);
p = NULL;
return 0;
}
2. 对动态开辟空间的越界访问
int main()
{
int* p = (int*)malloc(20);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
//可能会出现对NULL指针的解引用操作
//所以malloc函数的返回值要判断的
int i = 0;
//越界访问
for (i = 0; i < 10; i++)
{
p[i] = i;
}
free(p);
p = NULL;
return 0;
}
3.对非动态开辟内存使用free释放
对非动态开辟内存使用free释放
int main()
{
int arr[10] = { 1,2,3,4,5 };
int* p = arr;
//....
free(p);
p = NULL;
return 0;
}
4.使用free释放一块动态开辟内存的一部分
//使用free释放一块动态开辟内存的一部分
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
int i = 0;
//[1] [2] [3] [4] [5] [ ] [ ] [ ] [ ] [ ]
for (i = 0; i < 5; i++)
{
*p = i + 1;
p++;
}
//释放
free(p);
p = NULL;
return 0;
}
5. 对同一块动态内存多次释放
//对同一块动态内存多次释放
int main()
{
int*p = (int*)malloc(20);
if (p == NULL)
{
return 1;
}
//使用
//
free(p);
p = NULL;
//释放
free(p);
p = NULL;
return 0;
}
6.动态开辟内存忘记释放(内存泄漏)
void test()
{
int* p = (int*)malloc(20);
//使用
//存放1 2 3 4 5
}
int main()
{
test();
//
return 0;
}
int main()
{
while (1)
{
malloc(1);
}
return 0;
}
经典笔试题
题目1:
请问运行Test 函数会有什么样的结果?
void GetMemory(char* p)
{
p = (char*)malloc(100);
}
void Test(void)
{
char* str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
int main()
{
Test();
return 0;
}
改进方法1:
char* GetMemory()
{
char* p = (char*)malloc(100);
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory();
strcpy(str, "hello world");
printf(str);
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
改进方法2:
void GetMemory(char** p)
{
*p = (char*)malloc(100);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str);
strcpy(str, "hello world");
printf(str);
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
注意:
printf(str);是没问题的
int main()
{
char* p = "hehe\n";
printf("hehe\n");
printf("%s\n", "hehe");
return 0;
}
表达式"hehe\n"的值是首元素h的地址,char* p = “hehe\n”;指的是把h的地址放进p中,而str表示的也是地址,所以没错。
题目2:
请问运行Test 函数会有什么样的结果?
char* GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory();
printf(str);
}
int main()
{
Test();
return 0;
}
题目3:
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
int main()
{
Test();
return 0;
}
要记得用free()释放
题目4:
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
应该在free(str)后面及时将str置为空指针
C/C++程序的内存开辟
C/C++程序内存分配的几个区域:
- 栈区(stack):在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集中,效率很高,但是分配的内存容量有限。 栈区主要存放运行函数而分配的局部变量、函数参数、返回数据、返回地址等。
- 堆区(heap):一般由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收 。分配方式类似于链表。
- 数据段(静态区)(static)存放全局变量、静态数据。程序结束后由系统释放。
- 代码段:存放函数体(类成员函数和全局函数)的二进制代码。
有了这幅图,我们就可以更好的理解static关键字修饰局部变量的例子了。
实际上普通的局部变量是在栈区分配空间的,栈区的特点是在上面创建的变量出了作用域就销毁。
但是被static修饰的变量存放在数据段(静态区),数据段的特点是在上面创建的变量,直到程序结束才销毁 所以生命周期变长。
柔性数组
也许你从来没有听说过柔性数组(flexible array)这个概念,但是它确实是存在的。
C99 中,结构中的最后一个元素允许是未知大小的数组,这就叫做『柔性数组』成员。
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
有些编译器会报错无法编译可以改成:
typedef struct st_type
{
int i;
int a[];//柔性数组成员
}type_a;
柔性数组的特点
- 结构中的柔性数组成员前面必须至少一个其他成员。
- sizeof 返回的这种结构大小不包括柔性数组的内存。
- 包含柔性数组成员的结构用malloc ()函数进行内存的动态分配,并且分配的内存应该大于结构的大小,以适应柔性数组的预期大小。
柔性数组的优势
用柔性数组的方案1:
#include <string.h>
#include <errno.h>
#include <stdlib.h>
struct S
{
int n;
char c;
int arr[0];//柔性数组成员
};
int main()
{
// 8 + 40
struct S* ps = (struct S*)malloc(sizeof(struct S) + 10*sizeof(int));
if (ps == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
//使用
ps->n = 100;
ps->c = 'w';
int i = 0;
for (i = 0; i < 10; i++)
{
ps->arr[i] = i;
}
for (i = 0; i < 10; i++)
{
printf("%d\n", ps->arr[i]);
}
//调整arr数组的大小
struct S* ptr = (struct S*)realloc(ps, sizeof(struct S) + 20 * sizeof(int));
if (ptr == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
else
{
ps = ptr;
}
//使用
//...
//释放
free(ps);
ps = NULL;
//printf("%d\n", sizeof(struct S));//
return 0;
}
用结构中指针的方案2:
struct S
{
int n;
char c;
int* arr;
};
int main()
{
struct S* ps = (struct S*)malloc(sizeof(struct S));
if (ps == NULL)
{
perror("malloc");
return 1;
}
int*ptr = (int*)malloc(10 * sizeof(int));
if (ptr == NULL)
{
perror("malloc2");
return 1;
}
else
{
ps->arr = ptr;
}
//使用
ps->n = 100;
ps->c = 'w';
int i = 0;
for (i = 0; i < 10; i++)
{
ps->arr[i] = i;
}
//打印
for (i = 0; i < 10; i++)
{
printf("%d ", ps->arr[i]);
}
//扩容 - 调整arr的大小
ptr = realloc(ps->arr, 20 * sizeof(int));
if (ptr == NULL)
{
perror("realloc");
return 1;
}
else
{
ps->arr = ptr;
}
//使用
//释放
free(ps->arr);
ps->arr = NULL;
free(ps);
ps = NULL;
return 0;
}
区别:
连续的内存有益于提高访问速度,也有益于减少内存碎片