C语言之旅:动态内存管理

目录

一.为什么要有动态内存分配

二.malloc和free

2.1 malloc

2.2 free

2. 3malloc和free的使用

三. calloc 

四. raelloc

4.1 代码示例:

4.2 注意事项:

4.3 对动态开辟空间的越界访问

4.4 对非动态开辟内存使⽤free释放

4.5 使用free释放⼀块动态开辟内存的⼀部分

 4.6 对同⼀块动态内存多次释放

4.7 动态开辟内存忘记释放(内存泄漏)

4.8 内存的分布:

五.  练习

题目1:

题目2:

题目3:

题目4:

六.柔性数组

6.1 什么是柔性数组

6.2柔性数组的使用

6.3柔性数组的优势


一.为什么要有动态内存分配

int val = 20;//在栈空间上开辟四个字节 
char arr[10] = {0};//在栈空间上开辟10个字节的连续空间 

上述的开辟空间的⽅式有两个特点:

• 空间开辟大小是固定的。

• 数组在申明的时候,必须指定数组的⻓度,数组空间⼀旦确定了大小不能调整 但是对于空间的需求,不仅仅是上述的情况。有时候我们需要的空间大小在程序运⾏的时候才能知 道,那数组的编译时开辟空间的⽅式就不能满足了。

C语言引⼊了动态内存开辟,让程序员自己可以申请和释放空间,就比较灵活了。

二.malloc和free

2.1 malloc

malloc 是一个用于动态内存分配的库函数,它属于标准库 <stdlib.h>。malloc 函数允许你在程序运行时分配指定数量的字节,并返回一个指向所分配内存的指针。

void* malloc (size_t size);

如果内存分配成功,它将返回一个非空。

如果失败,它将返回 NULL。

返回值的类型是 void* ,所以malloc函数并不知道开辟空间的类型,具体在使⽤的时候使用者自己来决定。

• 如果参数 size 为0,malloc的⾏为是标准是未定义的,取决于编译器。

2.2 free

free 是一个用于释放之前由 malloc、calloc 或 realloc 函数分配的内存的函数。它定义在 <stdlib.h> 头文件中。

当你使用 malloc、calloc 或 realloc 函数在堆上分配内存时,你负责在不再需要这块内存时使用 free 函数来释放它。如果不这样做,你的程序将会消耗越来越多的内存,直到耗尽所有可用的内存,这通常会导致程序崩溃或其他不可预见的错误。

函数的原型如下:

void free(void *ptr);

free函数用来释放动态开辟的内存。

 • 如果参数 ptr 指向的空间不是动态开辟的,那free函数的⾏为是未定义的。

 • 如果参数 ptr 是NULL指针,则函数什么事都不做。 

2. 3malloc和free的使用

代码示例:

#include <stdlib.h>  
#include <stdio.h> 

int main() {
    int n = 5;   
    int* arr; 
    arr= (int*)malloc(n * sizeof(int));

    // 检查malloc是否成功分配了内存  
    if (arr == NULL) {
        printf("内存分配失败!\n");
        return 1; // 返回一个错误代码  
    }

    // 使用分配的内存  
    for (int i = 0; i < n; i++) 
    {
        arr[i] = i * 2; 
    }
   
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    // 释放分配的内存  
    free(arr);

    return 0; // 程序成功执行完毕  
}

三. calloc 

calloc 是 C 和 C++ 语言中的一个库函数,用于动态内存分配。与 malloc 函数相似,calloc 也用于在堆上分配内存,但它会额外地将分配的内存区域初始化为零。

calloc原型:

void *calloc(size_t num, size_t size);

参数:
num:要分配的元素数量。
size:每个元素的大小(以字节为单位)。

代码示例:

#include <stdlib.h>  
#include <stdio.h> 
int main() 
{
    int* ptr;
    int num = 5;
    int size = sizeof(int);

    // 使用 calloc 分配内存并初始化为零  
    ptr = (int*)calloc(num, size);

    if (ptr == NULL) 
    {
        perror("calloc");
        exit(0);
    }
    
    for (int i = 0; i < num; i++) 
    {
        printf("%d ", ptr[i]);  
    }
    free(ptr);

    return 0;
}

输出结果:

0 0 0 0 0

如果我们申请空间时要对其初始化,那么就可以用calloc。

四. raelloc

当我们申请分配了一块内存,但在程序执行过程中发现这块内存的大小不够或过大时,可以使用realloc来动态地调整其大小。

函数原型:

void *realloc(void *ptr, size_t size);

ptr:指向之前分配的内存块的指针。如果 ptr 为 NULL,则 realloc 的行为与 malloc 相同,即分配一块新的内存。
size:新分配的大小(以字节为单位)。

4.1 代码示例:

int main() {
    int* ptr = NULL;
    size_t Size = 4; // 初始分配4个整数的空间  

    // 初始内存分配  
    ptr = (int*)malloc(Size * sizeof(int));
    if (ptr == NULL) {
        perror("malloc");
        return 1;
    }

    // 初始化分配的内存空间  
    for (size_t i = 0; i < Size; ++i) 
    {
        ptr[i] = i + 1; 
    }

    // 打印初始数据  
    for (size_t i = 0; i < Size; ++i) 
    {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    // 扩展内存  
    Size *= 2;  
    int* Ptr1 = realloc(ptr, Size * sizeof(int));
    if (Ptr1 == NULL) 
    {
        perror("realloc");
        // 如果realloc失败,释放原始内存并退出程序  
        free(ptr);
        return 1;
    }

    // 如果realloc成功,更新ptr指针  
    ptr = Ptr1;

    // 初始化新分配的内存空间(这里仅初始化新增的部分)  
    for (size_t i = Size / 2; i < Size; ++i) 
    {
        ptr[i] = i + 1;   
    }
    
    for (size_t i = 0; i < Size; ++i) 
    {
        printf("%d ", ptr[i]);
    }
    printf("\n");
    free(ptr);
    ptr = NULL;

    return 0;
}

4.2 注意事项:

1. 检查malloc和realloc的返回值:确保malloc和realloc调用成功分配了内存。如果它们返回NULL,表示内存分配失败。

2. 不要直接对realloc的返回值进行操作:在将realloc的返回值赋给原始指针之前,先检查它是否为NULL。如果realloc失败,它会释放原始内存并返回NULL。如果你直接对realloc的返回值进行操作,而没有检查它是否为NULL,你可能会丢失对原始数据的引用,并且如果之后尝试访问原始数据,可能会导致程序崩溃。

3. 避免野指针:在释放内存后,将指针设置为NULL,以避免野指针。

五. 常⻅的动态内存的错误

5.1 对NULL指针的解引用操作

代码示例:

void test() 
{
    int* p = (int*)malloc(sizeof(int));
  
    *p = 20; 
    free(p); 
    p = NULL; 
}

malloc因为任何原因(如内存不足或整数溢出)未能成功分配内存,它会返回NULL。但是在这个函数中,没有检查malloc的返回值是否为NULL。如果p是NULL,那么解引用*p = 20;将会导致程序崩溃。

正确代码示例:

void test() 
{
    int* p = (int*)malloc(sizeof(int)); 
    if (p == NULL)     
    {
        // 处理内存分配失败的情况  
        perror("malloc ");
        return;
    }
    *p = 20;   
    free(p); // 释放内存  
    p = NULL; // 避免野指针 
}

4.3 对动态开辟空间的越界访问

代码示例:

void test()
{
	int i = 0;
	int* p = (int*)malloc(10 * sizeof(int));
	if (NULL == p)
	{
		perror("malloc");
		return;
	}
	for (i = 0; i <= 10; i++)
	{
		*(p + i) = i;//当i是10的时候越界访问 
	}
	free(p);
}

正确代码:

void test()
{
	int i = 0;
	int* p = (int*)malloc(10 * sizeof(int));
	if (NULL == p)
	{
		perror("malloc");
		return;
	}
	for (i = 0; i < 10; i++)
	{
		*(p + i) = i;
	}
	free(p);
}

4.4 对非动态开辟内存使用free释放

错误示范:

int main() 
{
    int a = 10; 
    int* ptr = &a; 

    // 错误的尝试
    free(ptr);   

    return 0;
}

在这个例子中,a是在栈上分配的,它的生命周期与包含它的函数相同。不能使用free来释放它,因为free只适用于通过malloc、calloc或realloc等函数在堆上动态分配的内存。

正确代码:

int main() 
{
    int* a = (int*)malloc(sizeof(int));     if (a == NULL) 
    { 
        return 1;
    }
    *a = 10;  
    free(a);
    a = NULL;  

    return 0;
}

4.5 使用free释放⼀块动态开辟内存的⼀部分

int main() 
{
    int* a = (int*)malloc(10 * sizeof(int)); 
    if (a == NULL) 
    {       
        perror("malloc");
        return 1;
    }
   
    for (int i = 0; i < 10; ++i) 
    {
        a[i] = i;
    }
    // 错误尝试:释放内存块的一部分   
    free(a + 5); 

    return 0;
}

正确的做法是保留原始指针a,并在不再需要整个内存块时调用free(a);来释放它。

正确代码示例:

int main() 
{
    int* a = (int*)malloc(10 * sizeof(int)); 
    if (a == NULL) 
    {
        perror("malloc");
        return 1;
    }
  
    for (int i = 0; i < 10; ++i) 
    {
        a[i] = i;
    }

    // 正确释放整个内存块  
    free(a);   
    a = NULL; // 避免野指针 
    return 0;
}

 4.6 对同⼀块动态内存多次释放

错误示例:

int main()
{
	int* a = (int*)malloc(10 * sizeof(int));
	if (a == NULL)
	{
		perror("malloc");
		return 1;
	}
	free(a);
	free(a);//重复释放
	return 0;
}

正确示范:

int main()
{
    int* a = (int*)malloc(10 * sizeof(int));
    if (a == NULL)
    {
        perror("malloc");
        return 1;  
    }
    free(a);
    a = NULL;
    return 0; 
}

4.7 动态开辟内存忘记释放(内存泄漏)

错误示例:

void test() 
{
    int* a = (int*)malloc(sizeof(int)); 
    if (a == NULL) 
    {     
        perror("malloc");
        exit(1);
    }
  
}

int main() 
{
    for (int i = 0; i < 1000; ++i) 
    {
        test(); // 每次调用都会泄漏一个int大小的内存  
    }  
    return 0;
}

在test函数每次调用都会分配一个新的int大小的内存块,但从未释放它。由于test在main函数的循环中被调用了1000次,因此程序结束时会有1000个int大小的内存块被泄漏。

正确做法在test函数中添加free函数进行释放。

切记:动态开辟的空间⼀定要释放,并且正确释放。

4.8 内存的分布:

五.  练习

题目1:

void GetMemory(char *p)
 {
 p = (char *)malloc(100);
 }
 void Test(void)
 {
 char *str = NULL;
 GetMemory(str);
 strcpy(str, "hello world");
 printf("%s\n", str);
 }

GetMemory 函数中分配的内存无法被 Test 函数中的 str 指针访问。因为 C 语言中函数参数是通过值传递的,所以 GetMemory 函数中接收到的 p 是 str 指针的一个副本。当 p 被重新分配内存后,原始的 str 指针在 Test 函数中并未改变,它仍然是一个空指针。

在 strcpy 函数调用中,将字符串 "hello world" 复制到 str 所指向的内存,但由于 str 是 NULL,这将导致程序崩溃。

正确写法:

void GetMemory(char** p) 
{
    *p = (char*)malloc(100); 
    if (*p == NULL) 
    {
  
        perror("malloc");
        exit(1);
    }
}

void Test(void)
{
    char* str = NULL;
    GetMemory(&str); 
    if (str != NULL) 
    {
        strcpy(str, "hello world");   
        printf("%s\n", str); 
        free(str);  
        str = NULL;
    }
}

题目2:

char *GetMemory(void)
 {
 char p[] = "hello world";
 return p;
 }
 void Test(void)
 {
 char *str = NULL;
 str = GetMemory();
 printf(str);
 }

GetMemory函数中的p是一个在栈上分配的字符数组,它包含了字符串"hello world"和一个的终止符\0。当GetMemory返回时,这个数组不再存在,但是str仍然指向原来的内存位置。因此,当在Test函数中使用str时,访问它会导致未定义,可能是崩溃,也可能是打印出其他值。

正确写法:

char* GetMemory(void)
{
    char* p = malloc(strlen("hello world") + 1);  // 分配足够的内存来存储字符串和终止符
    if (p == NULL) 
    {       
        perror("malloc");
        exit(1);
    }
    strcpy(p, "hello world");  
    return p; 
}

void Test(void)
{
    char* str = NULL;
    str = GetMemory();
    if (str != NULL) 
    {
        printf("%s\n", str); 
        free(str); 
    }
}

在这个修正后的代码中,GetMemory函数使用malloc在堆上分配足够的内存来存储字符串"hello world"和它的终止符。

题目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);
 }

未释放内存:应该在Test函数的末尾添加free(str);

正确写法:

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;

}

题目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指针并未被置为NULL,在if(str != NULL)检查中,这个条件始终为真。free(str)被调用后,str成为了一个野指针,因为它指向的内存已经被释放,但指针本身的值(内存地址)没有改变。

正确写法:

void Test(void)
{
    char* str = (char*)malloc(100);
    strcpy(str, "hello");
    free(str);
    str = NULL;
    if (str != NULL)
    {
        strcpy(str, "world");
        printf(str);
    }
}

六.柔性数组

6.1 什么是柔性数组

柔性数组,是C99标准中引入的一个特性.在C语言中,结构体的最后一个元素可以是一个大小未知的数组,这就是柔性数组。

typedef struct st_type
{
	int i;
	int a[0]; //柔性数组成员
};

有些编译器会报错无法编译可以改成:

typedef struct st_type
{
 int i;
 int a[];//柔性数组成员 
}type_a;

柔性数组的特点:

• 结构中的柔性数组成员前面必须至少⼀个其他成员。

• sizeof返回的这种结构大小不包括柔性数组的内存。

 • 包含柔性数组成员的结构用malloc()函数进行内存的动态分配,并且分配的内存应该大于结构的大小,以适应柔性数组的预期大小。

例如:

typedef struct st_type
{
	int i;
	int a[0];//柔性数组成员 
}type_a;
int main()
{
	printf("%d\n", sizeof(type_a));//输出的是4 
	return 0;
}

6.2柔性数组的使用

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int i;
    int a[]; 
} type_a;

int main()
{
    int i = 0;
    type_a* p = (type_a*)malloc(sizeof(type_a) + 100 * sizeof(int));
    //业务处理 
    p->i = 100;
    for (i = 0; i < 100; i++)
    {
        p->a[i] = i;
    }
    free(p);
    return 0;
}

6.3柔性数组的优势

代码示例:

#include <stdio.h>  
#include <stdlib.h>


typedef struct st_type
{
    int i;
    int* p_a; 
} type_a;

// 分配内存并初始化type_a结构体的函数  
type_a* c_type_a(int size) 
{
    type_a* p = (type_a*)malloc(sizeof(type_a));
    if (p == NULL) 
    {
        perror("malloc");
        return NULL;
    }

    p->p_a = (int*)malloc(size * sizeof(int));
    if (p->p_a == NULL) 
    {
        perror("malloc");
        free(p); 
        return NULL;
    }
    p->i = size; 

    for (int i = 0; i < size; i++) 
    {
        p->p_a[i] = 0;
    }
    return p;

}

int main() 
{
      
    type_a* ta = c_type_a(10);
    if (ta != NULL)
    {
       
        for (int i = 0; i < ta->i; i++) 
        {
            ta->p_a[i] = i;   
        }    
        for (int i = 0; i < ta->i; i++) 
        {
            printf("%d ", ta->p_a[i]);
        }
        printf("\n");
          
        free(ta->p_a);
        ta->p_a = NULL;
        free(ta);

    }

    return 0;

第⼀个好处是:方便内存释放.

如果我们的代码是在⼀个给别⼈用的函数中,你在⾥⾯做了⼆次内存分配,并把整个结构体返回给用户。⽤⼾调⽤free可以释放结构体,但是用户并不知道这个结构体内的成员也需要free,所以你不能 指望用户来发现这个事。所以,如果我们把结构体的内存以及其成员要的内存⼀次性分配好了,并返 回给用户⼀个结构体指针,用户做⼀次free就可以把所有的内存也给释放掉。

第⼆个好处是:这样有利于访问速度.

 连续的内存有益于提高访问速度,也有益于减少内存碎片。

  • 18
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值