关于malloc,calloc,free,realloc四个函数的使用
1.malloc
voidmalloc(size_t size)
这个函数向内存申请一块连续可用的空间,并返回指向这块空间的指针
如果开辟成功,返回指向开辟空间的指针
如果开辟失败,返回空指针
返回类型为void,malloc函数并不知道开辟空间的类型,具体的类型在使用的时候使用者自己来决定
如果参数size为0,malloc的行为是未定义的
2.free
voidfree(voidptr)
如果ptr指向的空间不是动态开辟的,那么free函数的行为是未定义的
如果ptr为空指针,那函数什么也不做
注意free释放的是空间
malloc与free的声明都放在#include<stdlib.h>中
int *ptr=NULL;
ptr=(int*)malloc(10*sizeof(int));
if(ptr!=NULL){
for(int i=0;i<10;i++){
ptr[i]=i+1;
}
for(int i=0;i<10;i++){
printf("%d ",ptr[i]);
}
}
free(ptr);
ptr=NULL;
3.calloc
allocate and zero-initialize array
allocates a block of memory for an array of num elements,each of them size bytes long,and initialize all its bits to zero.
void*calloc(size_t num,size_t size)
函数的功能是为num个大小为size的元素开辟一块空间,并把空间的每个字节初始化为0
calloc与malloc的对比
1.都是在堆上申请空间,与malloc的区别在于calloc在初始化的时候会将每个字节初始化为0
2.两者参数不同,malloc的参数就是要申请的字节数,而calloc的两个参数一个是要申请的元素个数,另一个是元素的字节数
4.realloc
voidrealloc(voidptr,size_t size)
realloc parameter
prt,pointer to memory block previously allocated by malloc,calloc,realloc.
Alternatively,this can be a null pointer,in which case a new block is allocated(as if malloc was called)
size,new size for memory block,int bytes.
size_t is an unsigned integral type.
ptr是要调整的内存地址
size 调整之后新大小
返回值为调整之后内存的起始位置
realloc在调整内存空间存在两种情况
情况一:原有空间之后有足够大的空间
要扩展内存就直接在原有内存之后追加空间,原来空间的数据不发生变化
情况二:原有空间之后没有足够多的空间
在堆空间上另找一个合适大小的连续空间来使用,这样函数返回的是一个新的内存地址
①.realloc会找更大的空间
②.将原来的数据拷贝到新的空间
③.释放旧的空间
④.返回新空间的地址
一般会先用一个临时指针ptr来接收realloc的返回值,当realloc的返回值不为NULL时,再p=ptr
(因为如果realloc返回一个空指针,那么之前p所指向的内存也丢失了),故要用一个临时指针来接收
int *p=NULL;
p=(int*)malloc(20);
for(i=0;i<4;i++){
p[i]=i+1;
}
int*ptr=NULL;
ptr=(int*)realloc(p,40);
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;
//注意:在这里只需要free(p)而不用free(ptr),因为p与q所指向的是同一块空间
realloc不仅可以调整空间,如果realloc的第一个参数为空指针,其也可以像malloc一样申请空间
realloc(NULL,20)等同于
malloc(20)
常见的动态内存错误
1.对NULL指针的解引用操作
int*p =(int*)malloc(20);
for(int i=0;i<5;i++){
p[i]=i+1;
}
//可能会出现对NULL指针的解引用,所以要对malloc函数的返回值进行判断
//因为malloc动态内存分配失败,会返回一个空指针
2.对动态开辟空间的越界访问
int*p=(int*)malloc(20);
if(p==NULL){
printf("%s\n",strerror(errno));
return 1;
}
for(int i=0;i<10;i++){
p[i]=i+1;
}
3.对非动态开辟内存的free释放
int a=10;
int*p=&a;
free(p);
4.使用free释放动态开辟内存的一部分
int*p=(int*)malloc(100);
p++;
free(p);//此时p已经不再指向动态内存的起始位置
5.对同一块内存多次释放
void test(){
int*p=(int*)malloc(100);
free(p);
free(p);//重复释放
}
6.动态开辟内存忘记释放(内存泄漏)
void test(){
int*p=(int*)malloc(100);
if(p!=NULL){
*p=20;
}
}
int main(){
test();
while(1);
}
堆上申请的空间在出了这个函数之后是不会回收的
malloc,calloc,realloc所申请的空间,如果不想使用,需要free释放,如果不释放,程序结束之后也会被操作系统回收,但如果既不释放,程序也没结束,就会造成内存泄露
忘记释放不再使用的动态开辟的内存会造成内存泄露
几道经典的面试题
1.
void getmemory(char*p){
p=(char*)malloc(100);
}
void Test(){
char*str=NULL;
getmemory(str);
strcpy(str,"hello world");
printf(str);
}
问题1:调用getmemory函数时,str的传参为值传递,**p仅仅只是str的一份临时拷贝(传值调用)**所以在getmemory内部将动态开辟的内存的地址存放在p中不会影响str,所以getmemory函数返回之后,strcpy函数就会调用失败,原因是对空指针进行了解引用操作,程序会崩溃
问题2: getmemory函数内部申请的空间没有机会释放,会造成内存泄漏
修改方法1:
void getmemory(char**p){
*p=(char*)malloc(100);
}
void Test(){
char*str=NULL;
getmemory(&str);
strcpy(str,"hello world");
printf(str);
}
修改方法2
char* getmemory(){
*p=(char*)malloc(100);
return p;
}
void Test(){
char*str=NULL;
str=getmemory();
strcpy(str,"hello world");
printf(str);
}
char* getmemory(){
char p[]="hello world";
return p;
}
void test(){
char*str=NULL;
str=getmemory();
printf(str);
}
返回栈空间地址的问题
getmemory函数内部创建的数组是临时的,虽然返回了数组的起始地址给str,但是数组的内存出了getmemory函数就被回收了,但是str依然保存了数组的起始地址,这时候如果再使用str,str就是野指针
void getmemory(char**p,int num){
*p=(char*)malloc(num);
}
void test(){
char*str=NULL;
getmemory(&str,100);
strcpy(str,"hello");
printf(str);
}
该题并无太大的问题,getmemory函数是传值调用,会真正修改str的指向,但问题在于没有及时释放str,故在结尾要加上
free(str);
str=NULL;
void test(){
char*str=(char*)malloc(100);
strcpy(str,"hello");
free(str);
if(str!=NULL){
strcpy(str,"hello");
printf(str);
}
}
问题在于free(str)即将str指向的空间释放,释放后就必须str=NULL;
如果此时不将str置为NULL,str就为野指针,因为str指向的动态分配的内存已经被回收
造成非法访问
c/c++程序内存分配的区域
1.内核空间kernel space(用户代码不能读写)
2.栈区 stack 在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束后这些存储单元被自动释放,栈内存分配运算内置于处理器的指令集中,效率很高,但是分配的内存容量有限。栈区主要存放运行函数而分配的局部变量、函数参数、返回数据、返回地址。
3.堆区 heap 一般由程序员分配释放,若程序员不释放,结束时由os回收(操作系统),分配方式类似于链表
4. 数据段(静态区) static 存放全局变量,静态数据,程序结束后由系统释放
5. 代码段:存放函数体(类成员函数和全局函数)的二进制代码
6. 内存映射段,文件映射,动态库,匿名映射
柔性数组(flexible array)
两种定义方式
struct S
{
int n;
char c;
int a[];
};
struct S
{
int n;
char c;
int a[0];
};
c99中,允许结构体的最后一个元素是未知大小的数组
柔性数组的特点:
1.结构体的柔性数组成员前面必须至少有一个成员
2.sizeof返回的这种结构体大小不包括柔性数组的内存
3.包括柔性数组成员的结构体用malloc()函数进行内存的动态分配,并且分配的内存应该大于结构体的大小以适应柔性数组的预期大小
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;
}
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;
}
//使用
for (i = 10;i < 20;i++) {
ps->arr[i] = i + 1;
}
for (i = 0;i < 20;i++) {
printf("%d ", ps->arr[i]);
}
//...
//释放
free(ps);
ps = NULL;
return 0;
}
柔性数组也可以用int*arr来代替,但是需要malloc两次,分别给struct s和arr分配空间
使用柔性数组malloc一次,free一次,容易维护空间不易出错,malloc次数少,内存碎片会较少,内存的使用率就会高一些
而且连续的内存有益于提高访问速度,也有益于减少内存碎片(局部性原理)
而不是用柔性数组,需要malloc两次,free两次,维护难度加大容易出错,malloc次数增多导致内存碎片增多,内存的使用率变低