1. 为什么存在动态内存分配
2. 动态内存函数的介绍
2.1 malloc和 free
void* malloc (size_t size);
这个函数向内存申请一块连续可用的空间,并返回指向这块空间的指针。
- 1、如果开辟成功,则返回一个指向开辟好空间的指针。
- 2、如果开辟失败,则返回一个NULL指针,因此malloc的返回值一定要做检查。
- 3、返回值的类型是 void* ,所以malloc函数并不知道开辟空间的类型,具体在使用的时候使用者自己来决定。
- 4、如果参数 size 为0,malloc的行为是标准是未定义的,取决于编译器。
C语言提供了另外一个函数free,专门是用来做动态内存的释放和回收的,函数原型如下:
void free (void* ptr);
free函数用来释放动态开辟的内存。
- 1、如果参数ptr指向的空间不是动态开辟的,那free函数的行为是未定义的。
- 2、如果参数ptr是NULL指针,则函数什么事都不做。
//变长数组
//c99标准支持变长数组
//int n = 0;
//scanf("%d", &n);
//int arr[n];
//动态内存开辟
#include <stdlib.h>
#include <stdio.h>
int main()
{
//假设开辟10个整形的空间 - 10* sizeof(int)
//int arr[10];//栈区
//动态内存开辟的
int* p = (int*)malloc(10*sizeof(int));//void*
//使用这些空间的时候
if (p == NULL)
{
//printf + strerror
perror("main");//main: xxxxxxxxx
return 1;
}
//使用
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *(p+i));//p[i] --> *(p+i)
}
//回收空间
free(p);
p = NULL;//自己动手把p置为NULL
return 0;
}
2.2 calloc
语言还提供了一个函数叫 calloc , calloc 函数也用来动态内存分配。
void* calloc (size_t num, size_t size);
- 1、函数的功能是为 num 个大小为 size 的元素开辟一块空间,并且把空间的每个字节初始化为0。
- 2、与函数 malloc 的区别只在于 calloc 会在返回地址之前把申请的空间的每个字节初始化为全0。
#include<stdio.h>
#include <stdlib.h>
int main()
{
//开辟10个整型空间
int* p = (int*)calloc(10, sizeof(int));
if (p == NULL)
{
perror("main");
return 1;
}
//打印
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));//0 0 0 0 0 0 0 0 0 0
}
//释放
free(p);
p = NULL;
return 0;
}
2.3 realloc
- realloc函数的出现让动态内存管理更加灵活。
- 有时会我们发现过去申请的空间太小了,有时候我们又会觉得申请的空间过大了,那为了合理的时 候内存,我们一定会对内存的大小做灵活的调整。那 realloc 函数就可以做到对动态开辟内存大小的调整。
void* realloc (void* ptr, size_t size);
- 1、ptr 是要调整的内存地址;size 是调整之后新大小
- 2、返回值为调整之后的内存起始位置。
- 3、这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到新的空间。
- 4、realloc在调整内存空间的是存在两种情况:
- 情况1:原有空间之后有足够大的空间。当是情况1 的时候,要扩展内存就直接原有内存之后直接追加空间,原来空间的数据不发生变化。
- 情况2:原有空间之后没有足够大的空间。当是情况2 的时候,原有空间之后没有足够多的空间时,扩展的方法是:在堆空间上另找一个合适大小的连续空间来使用。这样函数返回的是一个新的内存地址。
//realloc的扩容功能
#include<stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)malloc(10, sizeof(int));
if (p == NULL)
{
perror("main");
return 1;
}
//使用
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i + 1;
}
//这里需要p指向的空间更大,需要20个int的空间
//realloc调整空间
int* ptr = (int*)realloc(p, 20 * sizeof(int));
if (ptr != NULL)
{
p = ptr;
}
//使用
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));//1 2 3 4 5 6 7 8 9 10
}
//释放
free(p);
p = NULL;
return 0;
}
//realloc的开辟动态内存空间功能
#include<stdio.h>
#include <stdlib.h>
int main()
{
//这里功能类似于malloc,就是直接在堆区开辟40个字节
int* p = (int*)realloc(NULL, 40);
return 0;
}
3. 常见的动态内存错误
3.1 对NULL指针的解引用操作
//1.对NULL指针的解引用操作
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)malloc(100);
if (p == NULL)
{
return 1;
}
*p = 20;//如果p的值是NULL,就会有问题
free(p);
p = NULL;
return 0;
}
3.2 对动态开辟空间的越界访问
//2. 对动态开辟空间的越界访问
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)malloc(10 * sizeof(int));
if (p == NULL)
{
return 1;
}
int i = 0;
for (i = 0; i <= 10; i++)
{
p[i] = i;//当i是10的时候越界访问
}
free(p);
p = NULL;
return 0;
}
3.3 对非动态开辟内存使用free释放
//3. 使用free释放非动态开辟的空间
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 10;//栈区
int* p = &a;
//使用
free(p);//使用free释放非动态开辟的空间
p = NULL;
return 0;
}
3.4 使用free释放一块动态开辟内存的一部分
//4. 使用free释放动态内存中的一部分
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)malloc(10 * sizeof(int));
if (p == NULL)
{
return 1;
}
int i = 0;
for (i = 0; i < 5; i++)
{
*p = i;
p++;
}
//释放
free(p);//p不再指向动态内存的起始位置
p = NULL;
return 0;
}
3.5 对同一块动态内存多次释放
//5. 对同一块动态开辟的空间,多次释放
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)malloc(10 * sizeof(int));
//...
free(p);
//...
free(p);//重复释放 - 除非在上面p = NULL;
return 0;
}
3.6 动态开辟内存忘记释放(内存泄漏)
//6. 动态开辟的空间忘记释放- 内存泄漏 - 比较严重的
//代码1
#include <stdio.h>
#include <stdlib.h>
void test()
{
int* p = (int*)malloc(10 * sizeof(int));
//...
int flag = 0;
scanf("%d", &flag);//5
if (flag == 5)
return; //没有经过下一步的释放,导致内存泄露
free(p);
p = NULL;
}
int main()
{
test();
return 0;
}
//代码2
#include <stdio.h>
#include <stdlib.h>
int* test()
{
//开辟内存空间的函数
int* p = (int*)malloc(10 * sizeof(int));
if (p == NULL)
{
return p;
}
//...
return p;
}
int main()
{
int* ret = test();
//忘记释放了
return 0;
}
4. 几个经典的笔试题
4.1 题目1:
//str传给GetMemory函数的时候是值传递,所以GetMemory函数的形参p是str的一份临时拷贝。 //在GetMemory函数内部动态申请空间的地址,存放在p中,不会影响外边str, //所以当GetMemory函数返回之后,str依然是NULL。所以strcpy会失败。 //当GetMemory函数返回之后,形参p销毁,使得动态开辟的100个字节存在内存泄漏,无法释放。 //改正下列代码 #include <stdio.h> #include <stdlib.h> #include <string.h> 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 #include <stdio.h> #include <stdlib.h> #include <string.h> char* GetMemory() { char* p = (char*)malloc(100); return p; } void Test(void) { char* str = NULL; str = GetMemory(); strcpy(str, "hello world"); printf(str);//char *p = "hello world"; 是把"hello world"首字符'h'的地址传给printf //所以等价于printf("hello world") free(str); str = NULL; } int main() { Test(); return 0; } //改2 #include <stdio.h> #include <stdlib.h> #include <string.h> 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; }
4.2 题目2:
//GetMemory 函数内部创建的数组是在栈区上创建的
//出了函数,p数组的空间就还给了操作系统
//返回的地址是没有实际的意义,如果通过返回的地址,去访问内存就是非法访问内存的
#include<stdio.h>
char* GetMemory(void)
{
//返回栈空间的地址的问题
char p[] = "hello world";
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory();
printf(str);
}
int main()
{
Test();
return 0;
}
//与上述代码类似
#include<stdio.h>
void* test()
{
//返回栈空间的地址的问题
int a = 0;
return &a;
}
int main()
{
int* p = NULL;
printf("hehe\n");
printf("%d\n", p);
return 0;
}
4.3 题目3:
#include<stdio.h>
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
//记住要释放
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
4.4 题目4:
#include<stdio.h>
void Test(void)
{
char* str = (char*)malloc(100);
strcpy(str, "hello");
free(str);
str = NULL;//释放的时候记得置为空指针
if (str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
int main()
{
Test();
return 0;
}
5. C/C++程序的内存开辟
6. 柔性数组
也许你从来没有听说过柔性数组(flexible array)这个概念,但是它确实是存在的。
C99 中,结构中的最后一个元素允许是未知大小的数组,这就叫做『柔性数组』成员。
struct S
{
int n;
int arr[];//柔性数组成员 - 大小是未知
};
//typedef 将 struct st_type 替换为 type_a
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
6.1 柔性数组的特点:
- 1、结构中的柔性数组成员前面必须至少一个其他成员。
- 2、sizeof 返回的这种结构大小不包括柔性数组的内存。
- 3、包含柔性数组成员的结构用malloc ()函数进行内存的动态分配,并且分配的内存应该大于结构的大小,以适应柔性数组的预期大小。
#include<stdio.h>
struct S
{
int n;//4
int arr[0];//柔性数组成员 - 大小是未知
};
int main()
{
int sz = sizeof(struct S);
printf("%d\n", sz);//4 - 只有int n的大小
struct S s;//4
return 0;
}
6.2 柔性数组的使用
#include<stdio.h>
struct S
{
int n;//4
int arr[0];//大小是未知
};
int main()
{
//期望arr的大小是10个整形
struct S* ps = (struct S*)malloc(sizeof(struct S) + 10 * sizeof(int));
if (ps == NULL)
{
perror("main");
return 1;
}
ps->n = 10;
int i = 0;
for (i = 0; i < 10; i++)
{
ps->arr[i] = i;
}
//增加
struct S* ptr = (struct S*)realloc(ps, sizeof(struct S) + 20 * sizeof(int));
if (ptr != NULL)
{
ps = ptr;
ptr = NULL;
}
//使用
//释放
free(ps);
ps = NULL;
return 0;
}
6.3 柔性数组的优势 (与上述代码进行对比)
#include<stdio.h>
struct S
{
int n;
int* arr;
};
int main()
{
struct S* ps = (struct S*)malloc(sizeof(struct S));
if (ps == NULL)
{
return 1;
}
ps->n = 10;
ps->arr = (int*)malloc(10 * sizeof(int));
if (ps->arr == NULL)
{
return 1;
}
int i = 0;
for (i = 0; i < 10; i++)
{
ps->arr[i] = i;
}
//增加
int* ptr = realloc(ps->arr, 20 * sizeof(int));
if (ptr != NULL)
{
ps->arr = ptr;
}
//使用
//释放
free(ps->arr);
ps->arr = NULL;
free(ps);
ps = NULL;
return 0;
}