【C进阶】动态内存管理

本文深入探讨了C语言中的动态内存管理,包括malloc、free、calloc、realloc函数的使用和示例,以及动态内存管理中常见的错误示例,如内存泄漏。此外,还介绍了C99中的柔性数组特性及其使用方法。
摘要由CSDN通过智能技术生成

码字不易,对你有帮助 点赞/转发/关注 支持一下作者
微信搜公众号:不会编程的程序圆
看更多干货,获取第一时间更新

想看更好的排版可以阅读原文
点击阅读原文

思维导图


目录


正文


零 简单了解内存区域划分

一 动态内存函数

1.1 malloc

malloc -> memory allocate

void* malloc (size_t size)

size_t 类型就是 unsigned long

库函数:stdlib.h

解释:

分配 size 字节的未初始化内存。

若分配成功,则返回为任何拥有基础对齐的对象类型对齐的指针。

size 为零,则 malloc 的行为是实现定义的。例如可返回空指针。亦可返回非空指针;但不应当解引用这种指针,而且应将它传递给 free 以避免内存泄漏。

**参数:**size - 要分配的字节数

返回值:

成功时,返回指向新分配内存的指针。为避免内存泄漏,必须用 free()realloc() 解分配返回的指针。

失败时,返回空指针。

英文文档:

Allocate memory block

Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.

If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.

Parameters

size

Size of the memory block, in bytes.
size_t is an unsigned integral type.

Return Value

On success, a pointer to the memory block allocated by the function.

The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.

If the function failed to allocate the requested block of memory, a null pointer is returned.

例1:malloc
#include<stdio.h>
#include<stdlib.h>

int main(void) {
   

	int size;
	printf("请输入元素个数:");
	scanf("%d", &size);
	int* arr = (int*)malloc(size * sizeof(int));
	//内存申请失败返回 空指针
	if (arr == NULL) {
   
		printf("内存申请失败!\n");
		return 0;
	}
	for (int i = 0; i < size; i++) {
   
		arr[i] = i;
		printf("%d\n", i);
	}

	free(arr);
	return 0;
}
1.2 free

void free( void* ptr )

**头文件:**stdlib.h

解释:

解分配之前由 malloc()calloc()realloc() 分配的空间

ptr 为空指针,则函数不进行操作。

ptr 的值不等于之前从 malloc()calloc()realloc() 返回的值,则行为未定义。

ptr 所指代的内存区域已经被解分配,则行为未定义,即是说已经以ptr 为参数调用 free()realloc() ,而且没有后继的 malloc()calloc()realloc() 调用以 ptr 为结果。

若在 free() 返回后通过指针 ptr 访问内存,则行为未定义(除非另一个分配函数恰好返回等于 ptr 的值)。

参数: ptr - 指向要解分配的内存的指针

返回值:

**注意:**此函数接收空指针(并对其不处理)以减少特例的数量。不管分配成功与否,分配函数返回的指针都能传递给 free()

英文文档

Deallocate memory block

A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations.

If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior.

If ptr is a null pointer, the function does nothing.

Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location.

Paramaters

ptr

Pointer to a memory block previously allocated with malloc, calloc or realloc.

Return Value

none

If ptr does not point to a memory block previously allocated with malloc, calloc or realloc, and is not a null pointer, it causes undefined behavior.

1.3 calloc

void* calloc( size_t num, size_t size )

**头文件:**stdlib.h

解释:

num 个对象的数组分配内存,并初始化所有分配存储中的字节为零。

若分配成功,会返回指向分配内存块最低位(首位)字节的指针,它为任何类型适当地对齐。

size 为零,则行为是实现定义的(可返回空指针,或返回不可用于访问存储的非空指针)。

参数:

num - 对象数目

size - 每个对象的大小

返回值:

成功时,返回指向新分配内存的指针。为避免内存泄漏,必须用 free()realloc() 解分配返回的指针。

失败时,返回空指针。

注意:

因为对齐需求的缘故,分配的字节数不必等于 num*size

初始化所有位为零不保证浮点数或指针被各种初始化为 0.0 或空指针(尽管这在所有常见平台上为真)。

英文文档:

void* calloc (size_t num, size_t size);

Allocate and zero-initialize array

Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.

The effective result is the allocation of a zero-initialized memory block of (num*size) bytes.

If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.

Parameters

  • num

Number of elements to allocate.

  • size

Size of each element.

size_t - is an unsigned integral type.

Return Value

On success, a pointer to the memory block allocated by the function.

The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.

If the function failed to allocate the requested block of memory, a null pointer is returned.

例2:calloc
#include<stdio.h>
#include<stdlib.h>

int main(void) {
   

	int* p1 = (
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值