C 语言 malloc

17 Mar 2025 | 5 分钟阅读

本节将讨论在C编程语言中使用malloc进行动态内存分配。malloc是一个预定义的库函数,代表内存分配。malloc用于在程序运行时分配指定大小的内存块。这意味着当用户/程序员不知道程序中需要多少内存空间时,它会在运行时创建动态内存分配。

因此,它在运行时输入内存大小(以字节为单位),以保留一个连续的内存块,并返回一个void类型的指针,该指针可以被强制转换为任何类型的指针。使用malloc创建的动态内存不会在执行时初始化内存,因此内存块包含一些默认的垃圾值。malloc函数在stdlib.h头文件中定义。因此,在使用malloc函数时,我们需要在程序中使用<stdlib.h>头文件。

Malloc in C

语法

在上述语法中,byte_size是一个参数,它指定内存块的大小(以字节为单位),该大小传递给malloc函数以保留连续内存。malloc()函数返回一个void类型的指针,该指针可以被强制转换为任何已定义类型的指针。

检查是否使用malloc函数创建内存的程序

让我们考虑一个示例,检查在C编程语言中是否使用malloc函数创建了内存。

Program1.c

输出

Memory is created using the malloc() function

在上面的程序中,我们使用malloc()函数创建一个整数类型的动态内存,该函数返回一个整数指针指向基地址。如果if语句检查ptr是否等于NULL指针,如果该语句为真,则表示内存未创建。否则,内存通过malloc()函数成功创建。

使用malloc()函数创建动态内存的程序

让我们考虑一个示例,从用户获取大小作为输入,然后使用C编程语言中的malloc()函数在运行时输入数据。

Program2.c

输出

Enter the allocated size of memory 10
 Enter numbers from the user: 25
40
20
13
56
78
67
24
10
7
 Numbers are stores in contiguous memory:
 The number is: 25
 The number is: 40
 The number is: 20
 The number is: 13
 The number is: 56
 The number is: 78
 The number is: 67
 The number is: 24
 The number is: 10
 The number is: 7
 Memory is created using the malloc() function

使用free()函数释放内存空间

free()函数释放通过malloc()函数创建的动态内存分配。动态内存无法自行释放已占用的内存,即使程序结束,现有空间也仍然存在。因此,我们需要释放保留的内存,以便其他程序可以重用它。

语法

在上述语法中,我们将ptr传递给free()函数,它充当动态内存的引用或基地址,指向内存块。

Program3.c

输出

The number of elements to be entered:
10
 Memory is created using the malloc() function
 Enter the elements in allocated space: 45
12
67
89
34
56
25
25
67
34
 Elements are:
 45
 12
 67
 89
 34
 56
 25
 25
 67
 34
 The addition of stored elements is: 454