当前位置:网站首页>【动态内存管理】malloc&calloc和realloc和笔试题和柔性数组
【动态内存管理】malloc&calloc和realloc和笔试题和柔性数组
2022-06-12 08:26:00 【每天都要坚持刷题】
0 为什么存在动态内存管理?
char str[20]={0];
int arr[20]={0};上述的空间开辟的方式有两个特点:
- 空间开辟空间的大小是固定的
- 数组在申明的时候必须指定数组空间的大小,它在编译时分配所需要的内存
但是如果我们所需要的空间大小在程序编译时并不确定,而是到程序运行起来的时候才能知道,那上述的空间开辟的方式就不适合了,动态内存管理就应运而生。
定义局部变量开辟的内存和动态内存开辟的内存的区别:
- 开辟空间的位置:
- 定义局部变量开辟的空间:栈上随机位置
- 动态申请的空间: 堆上连续位置
- 释放:
- 定义局部变量开辟的空间:出代码块自动销毁
- 动态申请的空间:最好是程序员手动释放
1 malloc函数
函数原型:void* malloc(size_t size)
参数说明:size为要分配内存空间的大小,单位是字节

#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int main()
{
//函数原型:void* malloc(size_t size)
//向内存申请了40个字节的空间:
//如果申请成功返回这块空间的首地址
//如果申请失败返回空指针NULL
int* p1 = (int*)malloc(40);//这个开辟成功
int* p2 = (int*)malloc(INT_MAX+1);//这个开辟失败
//后面使用这块空间时会改变p的指向,所以用ptr保留这块空间的起始地址
int* ptr = p1;
//检验指针p的有效性:检测内存申请结果的返回值是否为NULL
if (p· == NULL)
{
perror("malloc");//malloc: Not enough space
exit(-1);
}
//开辟了40个字节,也就是10个int类型变量的大小
for (int i = 0; i < 10; i++)
{
*(p·++) = 0;
}
//释放ptr指针所指向的那块空间,但是ptr仍然保留着动态申请的那块空间的起始地址
free(ptr);
//让ptr指向空,使他失去对动态申请的那块空间的起始地址的记忆
ptr = NULL;
p=NULL;
return 0;
}当我们不手动释放动态内存开辟的空间:
- 如果程序结束,动态申请的内存由OS自动回收
- 但是如果程序始终不结束,动态内存申请的那块空间不会自动释放,就会造成内存泄漏问题。 (程序结束肯定会自动释放动态申请的内存,不然内存肯定会越写越少,谁还敢写代码;但是当这块空间占用的时间太长,而且这块空间开辟的比较大,就会比较吃内存)
2 calloc函数
函数原型:void* calloc(size_t num,size_t size)
参数说明:num是要分配size字节大小的空间的元素个数

malloc 和 calloc 的区别: calloc在申请内存空间的同时将这块空间初始化为0了
int main()
{
//函数原型: void* calloc(size_t num,size_t size)
//元素个数:10
//每个元素所占的字节数:sizeof(int)
int* p = (int*)calloc(10, sizeof(int));
int* ptr = p;
if (p == NULL)
{
perror("calloc");
exit(-1);
}
for (int i = 0; i < 10; i++)
{
printf("%d\t", *(p++));
}
free(ptr);
ptr = NULL;
p = NULL;
}
3 realloc函数
有了realloc函数,我们就可以已经malloc或calloc开辟好且对容量不满意的空间进行重新调整。(调整:调大调小均可)
重新分配内存空间函数:void* realloc(void* ptr,size_t size)
参数说明:ptr为指向那块需要重新分配内存空间的那块空间,size为需要重新分配的空间大小,单位是字节。
下面以扩容为例:
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
perror("malloc");
exit(-1);
}
for (int i = 0; i < 10; i++)
{
*(p + i) = i;//p没有改变指向
}
//希望放20个元素,空间不够,考虑用realloc扩容
int p = (int*)realloc(p, 80);//error,万一realloc扩容失败,p接收到的是空指针,把原来p的指向覆盖(弄丢)了
//函数原型:void* realloc(void* ptr,size_t size)
//ptr:一个指针,指针指向的是扩容的空间的起始地址
//size:扩容成功后希望得到的字节数
int* temp = (int*)realloc(p, 80);//bingo
if (temp != NULL)
{
p = temp;
}
free(p);
p = NULL;
return 0;
}realloc调整空间:
- 如果要缩小空间:则在原空间上截取相应长度的空间,并返回原的首地址(也就是等于p)
- 如果是扩大空间,分以下3种情况:
- 如果原空间在内存中的位置能够开辟出扩容后的所需要的空间大小,就相应开辟,并返回新空间的起始地址。
- 如果原空间在内存中的位置不能够开辟出扩容后所需要的空间大小,OS就会在堆内存中找一块足够容纳所需空间大小的一块新空间,将原空间里的值复制到新空间,并返回新空间的起始地址
- 如果在堆内存中的任意位置都不够开辟所需要的内存空间大小,则返回空指针。
4 常见的动态内存错误
int main()
{
//way1:对NULL指针进行解引用
int* p = (int*)malloc(INT_MAX + 1);
//直接使用//error
//way2:越界访问
int* p = (int*)malloc(40);
if (p == NULL)
{
perror("malloc");
exit(-1);
}
for (int i = 0; i < 11; i++)//error
{
*(p + i) = i;
}
//way3:使用free函数释放非动态申请的内存
int a = 10;
int* p = &a;
free(p);//error
p = NULL;
//way4:使用free函数释放动态申请的内存的一部分
int* p = (int*)malloc(40);
if (p == NULL)
{
perror("malloc");
exit(-1);
}
for (int i = 0; i < 11; i++)//error
{
*p = i;
p++;
}
free(p);//error
p = NULL;
//way5:对同一块动态申请的内存多次释放
free(p);
free(p);
p = NULL;
//way6:忘记释放动态申请的内存
return 0;
}5 2道经典的笔试题:
笔试题1:下面代码能打印出hello world吗?------>传值和传址
//错误代码:
void Getmory(char* p)
{
p = (char*)malloc(100);
}
void test(void)
{
char* str = NULL;
Getmory(str);
strcpy(str, "hello world");
printf(str);
}
int main()
{
test();
return 0;
}答案:不能,按照代码本意:想通过Getmory函数给str动态开辟一段100个字节的空间,然后使用strcpy函数拷贝字符串‘hello world’并打印出来。
问题在于:Getmory函数的函数参数只是字符指针str的一份临时拷贝,形参的改变p不影响实参str,而且这样的话,p指向的那段空间在p所在的代码块内都没有得到释放,出Getmory函数代码块后,局部变量p被销毁,这段动态申请的空间也就没有得到销毁,也无法再销毁。
另外,连锁反应,str还是指向空,strcpy函数执行的时候由于源空间不够容纳"hello world“
,就会出现第二个问题。
正确代码:
//正确代码:
void Getmory(char** p)
{
*p = (char*)malloc(100);
}
void test(void)
{
char* str = NULL;
Getmory(&str);
strcpy(str, "hello world");
printf(str);
}
int main()
{
test();
return 0;
}

笔试题2:下面的代码能打印出"hello world“吗”-------->“返回栈空间地址问题”
//错误代码:
char* Getmory(void)
{
char p[] = "hello world";
return p;
}
void test()
{
char* str = NULL;
str = Getmory();
printf(str);
}
int main()
{
test();
return 0;
}答案:不能,Getmory函数中,"hello world”被放在了一个字符数组里,返回时返回的是数组名,也就是这个数组首元素的地址,Getmory函数结束时字符数组所占用的空间自动销毁,但是返回了栈空间的地址,一旦在test函数内对这地址解引用进行访问,那就是非法的,未知的,上述代码的错误原因和下述代码的错误类似。
//错误代码
int* test()
{
int a = 10;
return &a;
}
int main()
{
int* p=test();
*p = 10;
printf("%d\n", *p);
printf("%d\n", *p);
return 0;
}6 柔性数组
柔性数组:结构中的最后一个元素允许是未知大小的数组,这就和叫做【柔性数组】成员。
struct s
{
int num;
double e;
int arr[0];
//或int arr[0];
};柔性数组的特点:
- 结构体中柔性数组成员前必须包含至少一个其他非柔性数组成员。
- 包含柔型数组的结构体的内存大小不包含柔型数组的内存大小。
- 包含柔性数组的结构体在开辟内存时得使用malloc函数动态内存开辟,且开辟的空间大小必须大于结构体的大小,以适应柔型数组的预期大小。
struct s
{
int num;
int arr[0];
//或int arr[0];
};
int main()
{
printf("sizeof(struct s):>%d\n", sizeof(struct s));
struct s* ps = (struct s*)malloc(sizeof(struct s) + 40);
ps->num = 100;
for (int i = 0; i < 10; i++)
{
ps->arr[i] = i;
}
for (int i = 0; i < 10; i++)
{
printf("%d\t", ps->arr[i]);
}
return 0;
}
struct s
{
int num;
int arr[0];
//或int arr[0];
};
int main()
{
printf("sizeof(struct s):>%d\n", sizeof(struct s));
struct s* ps = (struct s*)malloc(sizeof(struct s) + 40);
if (ps == NULL)
{
perror("malloc");
exit(-1);
}
ps->num = 100;
for (int i = 0; i < 10; i++)
{
ps->arr[i] = i;
}
for (int i = 0; i < 10; i++)
{
printf("%d\t", ps->arr[i]);
}
//柔性数组的柔性含义:可以realloc扩容
struct s* temp = (struct s*)realloc(ps, sizeof(struct s) + 80);
if (temp != NULL)
{
ps = temp;
}
for (int i = 0; i < 20; i++)
{
ps->arr[i] = i;
}
for (int i = 0; i < 20; i++)
{
printf("%d\t", ps->arr[i]);
}
free(ps);
ps = NULL;
return 0;
}

边栏推荐
- Convolutional neural network CNN based cat dog battle picture classification (tf2.1 py3.6)
- Hands on deep learning -- discarding method and its code implementation
- ctfshow web 1-2
- 安科瑞消防应急照明和疏散指示系统
- Hands on learning and deep learning -- simple implementation of linear regression
- 牛客网的项目梳理
- APS究竟是什么系统呢?看完文章你就知道了
- 只把MES当做工具?看来你错过了最重要的东西
- ctfshow web3
- What is the difference between ERP production management and MES management system?
猜你喜欢
![Easyexcel exports excel tables to the browser, and exports excel through postman test [introductory case]](/img/ca/0e2bd54a842a393231ec6db5ab02c2.png)
Easyexcel exports excel tables to the browser, and exports excel through postman test [introductory case]

FPGA implementation of right and left flipping of 720p image

X64dbg debugging exception_ ACCESS_ VIOLATION C0000005

Hands on deep learning -- weight decay and code implementation

Hands on deep learning -- implementation of multi-layer perceptron from scratch and its concise implementation

Hands on deep learning -- image classification dataset fashion MNIST

Hands on deep learning -- discarding method and its code implementation

企业为什么要实施MES?具体操作流程有哪些?

(p40-p41) transfer and forward perfect forwarding of move resources

Hands on learning and deep learning -- simple implementation of linear regression
随机推荐
Figure neural network makes Google maps more intelligent
(P19-P20)委托构造函数(代理构造函数)和继承构造函数(使用using)
call方法和apply方法
Hands on learning and deep learning -- simple implementation of linear regression
S-msckf/msckf-vio technical route and code details online blog summary
牛客网的项目梳理
MPLS的原理与配置
Gtest/gmock introduction and Practice
如何理解APS系统的生产排程?
DUF:Deep Video Super-Resolution Network Using Dynamic Upsampling Filters ... Reading notes
Quaternion Hanmilton and JPL conventions
CMAKE 里PRIVATE、PUBLIC、INTERFACE属性示例详解
ctfshow web3
Arrays in JS
Summary of 3D point cloud construction plane method
Regular expressions in JS
How to understand the production scheduling of APS system?
What kind of sparks will be generated when the remote sensing satellite meets the Beidou navigation satellite?
(p27-p32) callable object, callable object wrapper, callable object binder
Vision transformer | arXiv 2205 - TRT vit vision transformer for tensorrt