C语言中高效灵活的动态内存分配函数:mynewcreate238


在C语言编程中,动态内存分配是一项重要的技能,它允许程序在运行时根据需要分配和释放内存。标准库函数malloc和calloc虽然功能强大,但使用起来不够灵活,也缺乏对分配失败的更高级处理机制。本文将介绍一个名为mynewcreate的自定义函数,它在malloc和calloc的基础上进行了改进,提供更安全、更灵活的动态内存分配功能,并演示如何有效地避免内存泄漏。

mynewcreate函数旨在提供以下增强功能:
错误处理: 在内存分配失败时,mynewcreate会打印出友好的错误信息并返回NULL,避免程序崩溃。
类型安全: 函数接受数据类型作为参数,从而增强类型安全,减少因类型转换错误导致的bug。
初始化: 可以选择性地将分配的内存初始化为零,类似于calloc的功能,但更灵活。
可扩展性: 函数设计简洁,易于扩展,可以根据需要添加其他功能,例如内存池管理或自定义的内存分配策略。

以下是mynewcreate函数的C语言实现:```c
#include
#include
#include
void *mynewcreate(size_t size, size_t count, int initialize, const char *filename, int line) {
void *ptr = NULL;
size_t total_size = size * count;
if (total_size == 0 && count != 0) {
fprintf(stderr, "Error in mynewcreate (file: %s, line: %d): Size cannot be zero when count is not zero.", filename, line);
return NULL;
}
if (total_size > 0 && count > (SIZE_MAX / size) ) {
fprintf(stderr, "Error in mynewcreate (file: %s, line: %d): Integer overflow detected.", filename, line);
return NULL;
}

ptr = malloc(total_size);
if (ptr == NULL) {
fprintf(stderr, "Error in mynewcreate (file: %s, line: %d): Memory allocation failed.", filename, line);
return NULL;
}
if (initialize) {
memset(ptr, 0, total_size);
}
return ptr;
}
// Example usage with macro for easier error tracking
#define MYNEWCREATE(type, count, init) mynewcreate(sizeof(type), count, init, __FILE__, __LINE__)
int main() {
int *arr = (int *)MYNEWCREATE(int, 10, 1); // Allocate and initialize an array of 10 integers
if (arr == NULL) {
return 1; //Handle allocation failure
}
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]); // Output: 0 0 0 0 0 0 0 0 0 0
}
printf("");
free(arr); // Remember to free the allocated memory
double *data = (double*)MYNEWCREATE(double, 5, 0); // Allocate 5 doubles, uninitialized
if (data == NULL) {
return 1;
}
for(int i=0; i

2025-06-18


上一篇:C语言中的初始化函数:深入理解和最佳实践

下一篇:C语言求解最小公倍数(LCM)与最大公约数(GCD)详解