C 动态分配内存


malloc 和 free 

void *malloc(size_t size);

void free(void *pointer);

 

calloc 和 realloc

void *calloc(size_t num_elements, size_t elements_size);

void realloc(void *ptr, size_t new_size); 

 

 1 
 2 /*
 3  * alloc.h
 4  *
 5  * 定义一个不易发生错误的内存分配器
 6  */
 7 
 8 #include <stdlib.h>
 9 
10 #define malloc
11 #define MALLOC(num,type) (type *)alloc((num) * sizeof(type))
12 
13 void *alloc(size_t size);
14 

 

/*
 * alloc.c
 *
 * 不易发生错误的内存分配器的实现
 
*/

#include 
<stdio.h>
#include 
"alloc.h"
#undef malloc

void *alloc(size_t size)
{
     
void *new_mem;
     new_mem 
= malloc(size);
     
if(new_mem == NULL)
     {
         printf(
"Out of memory!\n");
         exit(
1);
     }
 
     
return new_mem;
}

 

相关文章:

  • 2022-01-18
  • 2021-09-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-17
  • 2021-12-05
  • 2021-04-30
  • 2021-07-25
  • 2021-08-30
  • 2021-10-23
相关资源
相似解决方案