C语言进阶——动态内存管理

简介: C语言进阶——动态内存管理

文章目录

  1. 为什么存在动态内存
  2. 分配动态内存函数的介绍
  1. 常见的动态内存错误
  1. 几个经典的笔试题
  1. C/C++程序的内存开辟
  2. 动态通讯录
  3. 为什么存在动态内存

我们经常用到的开辟内存方式有:

int a = 40;
int arr[40] = {0};

  1. 分配动态内存函数的介绍

2.1 malloc
C语言提供了一个动态内存开辟的函数: 

void* malloc (size_t size);

define _CRT_SECURE_NO_WARNINGS

include<stdio.h>

include<stdlib.h>

include<string.h>

include<errno.h>

int main()
{

int arr[10] = { 0 };
//动态内存开辟
int* p = (int*)malloc(40);
if (p == NULL)
{
    printf("%s\n", strerror(errno));
    return 1;
}
//使用
int i = 0;
for (i=0;i<10;i++)
{
    *(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));
}
printf("\n");

return 0;

}

 这里没有free,当程序退出的时候, 系统会回收该空间

2.2 free
C语言提供了另外一个函数free,专门是用来做动态内存的释放和回收的,函数原型如下: 

void free (void* ptr);

int main()
{

int arr[10] = { 0 };
//动态内存开辟
int* p = (int*)malloc(40);
if (p == NULL)
{
    printf("%s\n", strerror(errno));
    return 1;
}
//使用
int i = 0;
for (i=0;i<10;i++)
{
    *(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d", *(p + i));
}

//释放
free(p);
p = NULL;

return 0;

}
不用free函数释放空间会出现内存泄漏,free回收完系统空间时,p还是指向那块吧被释放的空间,为了避免出现野指针的问题,一定要将它置为空指针

2.3 calloc
C语言还提供了一个函数叫calloc,calloc函数也用来动态内存分配。原型如下:

void* calloc (size_t num, size_t size);

define _CRT_SECURE_NO_WARNINGS

include<stdio.h>

include<stdlib.h>

include<string.h>

include<errno.h>

int main()
{

int arr[10] = { 0 };
//动态内存开辟
int* p = (int*)calloc(10,sizeof(int));
if (p == NULL)
{
    printf("%s\n", strerror(errno));
    return 1;
}
//使用
/*int i = 0;
for (i=0;i<10;i++)
{
    *(p + i) = i;
}*/
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));
}
printf("\n");
free(p);
p = NULL;

return 0;

}

 所以如何我们对申请的内存空间的内容要求初始化,那么可以很方便的使用calloc函数来完成任务

2.4 realloc
realloc函数的出现让动态内存管理更加灵活

有时会我们发现过去申请的空间太小了,有时候我们又会觉得申请的空间过大了,那为了合理的时候内存,我们一定会对内存的大小做灵活的调整。那realloc函数就可以做到对动态开辟内存大小的调整。函数原型如下:

void realloc (void ptr, size_t size);

define _CRT_SECURE_NO_WARNINGS

include<stdio.h>

include<stdlib.h>

include<string.h>

include<errno.h>

int main()
{

int arr[10] = { 0 };
//动态内存开辟
int* p = (int*)malloc(40);
if (p == NULL)
{
    printf("%s\n", strerror(errno));
    return 1;
}
//使用
int i = 0;
for (i=0;i<10;i++)
{
    *(p + i) = i+1;
}
//扩容
//追加40个字节
int *ptr = (int* )realloc(p, 80);

if (ptr != NULL)
{
    p = ptr;
}
//使用
for (i = 0; i < 10; i++)
{
    printf("%d ", *(p + i));
}
printf("\n");
free(p);
p = NULL;

return 0;

}
注意:开辟多了会出现内存碎片,导致内存利用率下降,程序的效率也会下降 

  1. 常见的动态内存错误

3.1 对NULL指针的解引用操作
int main()
{

int* p = (int*)malloc(40);
if (p == NULL)
{
    return 1;
}
*p = 20;
free(p);
p = NULL;
return 0;

}
要判断是否为空指针,如果是空指针就是开辟内存失败,出现对空指针的解引用

3.2 对动态开辟空间的越界访问
int main()
{

int* p = (int*)malloc(40);
if (p == NULL)
{
    printf("%s", strerror(errno));
}
int i = 0;
for (i = 0; i <= 10; i++)
{
    p[i] = i;
}

free(p);
p = NULL;
return 0;

}

 当i是10的时候越界访问

3.3 对非动态开辟内存使用free释放
void test()
{

int a = 10;
int* p = &a;
free(p);
p = NULL;

}
int main()
{

test();
return 0;

}
free函数只能对在堆上开辟的动态内存进行释放

3.4 使用free释放一块动态开辟内存的一部分
int main()
{

int* p = (int*)malloc(40);
if (p == NULL)
{
    printf("%s", strerror(errno));
}
int i = 0;
for (i = 0; i <= 10; i++)
{
    *p = i;
    p++;
}
//释放
free(p);
p = NULL;
return 0;

}

 程序运行起来,p已经不指向最开始的地址,因此最后释放,也不会将动态开辟的内存全部释放

3.5 对同一块动态内存多次释放
int main()
{

int* p = (int*)malloc(40);

free(p);
//.....
free(p);

return 0;

}
重复释放并且没有将p置为空指针,会报错

3.6 动态开辟内存忘记释放(内存泄漏)
void test()
{

int* p = (int*)malloc(40);
//....
int a = 0;
scanf("%d", &a);
//...
if (a == 10)
    return;

free(p);
p == NULL;

}

int main()
{

test();

return 0;

}
当满足a==10,free是没有机会被执行的,并且函数结束就找不到该空间的地址了,也不会释放,内存出现泄漏

注意:忘记释放不再使用的动态开辟的空间会造成内存泄漏

动态开辟的空间一定要释放,并且正确释放

  1. 几个经典的笔试题

笔试题1 
void GetMemory(char* p)
{

p= (char*)malloc(100);

}
void Test(void)
{
char* str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
解析:

笔试题2
char* GetMemory(void)
{

char p[] = "hello world";
return p;

}
void  Test(void)

{

char*str = NULL;
str = GetMemory();
printf(str);

}
 解析:

笔试题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);

}
 分析:

笔试题4
void Test(void)
{

char* str = (char*) malloc(100);
strcpy(str, "hello");
free(str);

if(str != NULL)
{

strcpy(str,"world");
printf(str);

}
}
分析:

  1. C/C++程序的内存开辟
  2. 动态通讯录

参看静态通讯录

pragma once

include<stdio.h>

include<string.h>

include<assert.h>

include<stdlib.h>

define MAX 100

define MAX_NAME 20

define MAX_SEX 10

define MAX_TELE 12

define MAX_ADDR 30

define DEFAULT_Sz 3

define INC_SZ 2

//类型的声明
//
//只是一个人的信息
typedef struct PeoInfo
{

char name[MAX_NAME];
int age;
char sex[MAX_SEX];
char tele[MAX_TELE];
char addr[MAX_ADDR];

}PeoInfo;

//静态版本
////通讯录(多个人的信息)
//typedef struct Contact
//{
// PeoInfo data[100];//存放人的信息
// int count;//记录当前通讯录有多少人的信息
//}Contact;
//
//
//动态版本
typedef struct Contact
{

PeoInfo* data;//存放人的信息
int count;//记录当前通讯录有多少人的信息
int capacity;//记录当前通讯录容量

}Contact;

//初始化通讯录函数
int InitContact(Contact *pc);

//增加联系人到通讯录
void addContact(Contact* pc);

//打印通讯录信息
void showContact(const Contact* pc);

//删除指定联系人
void delContact(Contact* pc);

//查找指定联系人
void SearchContact(Contact* pc);

//修改指定联系人
void modifyContact(Contact* pc);

//按照名字排序通讯录内容
void sortContact(Contact* pc);
//销毁通讯录
void DestroyContact(Contact* pc);

//动态版本
int InitContact(Contact* pc)
{

pc->count = 0;
pc->data = (PeoInfo*)calloc(DEFAULT_Sz,sizeof(PeoInfo));
if (pc->data == NULL)
{
    printf("InitContact:%s\n", strerror(errno));
    return 1;
}
pc->capacity = DEFAULT_Sz;
return 0;

}
 实现增容功能:

//增容函数
void CheckCapacity(Contact* pc)
{

if (pc->count == pc->capacity)
{
    PeoInfo* ptr = (PeoInfo*)realloc(pc->data, (pc->capacity + INC_SZ) * sizeof(PeoInfo));
    if (ptr == NULL)
    {
        printf("addContact:%s\n", strerror(errno));
    }
    else
    {
        pc->data = ptr;
        pc->capacity += INC_SZ;
        printf("增容成功\n");
    }
}

}

//动态版本
void addContact(Contact* pc)
{

assert(pc);
//增容
CheckCapacity(pc);

//添加信息
printf("\n请输入名字:>");
//每次放进去的信息都是放进data 下标为count的数组
scanf("%s", pc->data[pc->count].name);

printf("\n请输入年龄:>");
//因为name是存放在数组中,数组名本身就是地址,不需要再取地址
//这里的年龄是int 型变量,需要取地址
scanf("%d", &(pc->data[pc->count].age));

printf("\n请输入性别:>");
scanf("%s", pc->data[pc->count].sex);

printf("\n请输入电话:>");
scanf("%s", pc->data[pc->count].tele);

printf("\n请输入地址:>");
scanf("%s", pc->data[pc->count].addr);

pc->count++;
printf("\n增加成功\n");

}
 free增容所开辟的空间:

//销毁通讯录
void DestroyContact(Contact* pc)
{

assert(pc);
free(pc->data);
pc->data = NULL;

}

相关文章
|
23天前
|
存储 编译器 C语言
【C语言篇】数据在内存中的存储(超详细)
浮点数就采⽤下⾯的规则表⽰,即指数E的真实值加上127(或1023),再将有效数字M去掉整数部分的1。
|
3月前
|
C语言
指针进阶(C语言终)
指针进阶(C语言终)
|
8天前
|
存储 大数据 C语言
C语言 内存管理
本文详细介绍了内存管理和相关操作函数。首先讲解了进程与程序的区别及进程空间的概念,接着深入探讨了栈内存和堆内存的特点、大小及其管理方法。在堆内存部分,具体分析了 `malloc()`、`calloc()`、`realloc()` 和 `free()` 等函数的功能和用法。最后介绍了 `memcpy`、`memmove`、`memcmp`、`memchr` 和 `memset` 等内存操作函数,并提供了示例代码。通过这些内容,读者可以全面了解内存管理的基本原理和实践技巧。
|
8天前
|
缓存 Linux C语言
C语言 多进程编程(六)共享内存
本文介绍了Linux系统下的多进程通信机制——共享内存的使用方法。首先详细讲解了如何通过`shmget()`函数创建共享内存,并提供了示例代码。接着介绍了如何利用`shmctl()`函数删除共享内存。随后,文章解释了共享内存映射的概念及其实现方法,包括使用`shmat()`函数进行映射以及使用`shmdt()`函数解除映射,并给出了相应的示例代码。最后,展示了如何在共享内存中读写数据的具体操作流程。
|
29天前
|
存储 程序员 C语言
【C语言】动态内存管理
【C语言】动态内存管理
|
1月前
|
存储 编译器 C语言
C++内存管理(区别C语言)深度对比
C++内存管理(区别C语言)深度对比
58 5
|
1月前
|
C语言
C语言动态内存管理
C语言动态内存管理
26 4
|
19天前
|
存储 NoSQL 程序员
C语言中的内存布局
C语言中的内存布局
24 0
|
23天前
|
C语言
【C语言篇】字符和字符串以及内存函数详细介绍与模拟实现(下篇)
perror函数打印完参数部分的字符串后,再打印⼀个冒号和⼀个空格,再打印错误信息。
|
23天前
|
存储 安全 编译器
【C语言篇】字符和字符串以及内存函数的详细介绍与模拟实现(上篇)
当然可以用scanf和printf输入输出,这里在之前【C语言篇】scanf和printf万字超详细介绍(基本加拓展用法)已经讲过了,这里就不再赘述,主要介绍只针对字符的函数.