第十一章:动态内存分配
void *malloc(size_t size)
void calloc(szie_t num_elements, size_t element_size)
void realloc(void *ptr,size_t new_size)
void free(void *ptr)
- 常见错误:忘记检查是否分配成功 ;操作内存超出分配内存的边界
- 定义如下不易发生错误的内存分配器,分别在文件
alloc.h alloc.c test.c
#ifndef CPOINTER_ALLOC_H
#define CPOINTER_ALLOC_H
#include <stdlib.h>
#define malloc //禁止直接调用malloc
#define MALLOC(num,type) (type *) alloc((num) * sizeof(type))
extern void *alloc(size_t size);
#endif //CPOINTER_ALLOC_H
#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;
}
#include "alloc.h"
int main(void )
{
int *new_memory;
new_memory = MALLOC(25,int);
}
-
动态内存分配实例
/*Example 1:读取、排序和打印一列整型值。*/ #include <stdio.h> #include <stdlib.h> /*比较整型值*/ int compare_integers (void const * a, void const * b) { register int const *pa = a; register int const *pb = b; return *pa > *pb ? 1: *pa < *pb - 1 ? -1 : 0; } int main(void) { int *array; int n_values; int i; /*询问有多少个数*/ printf("How many values are here?"); if (scanf("%d", &n_values) != 1 || n_values <= 0) { printf("Illegal number of values.\n"); exit(EXIT_FAILURE); } /*分配内存*/ array = malloc(n_values * sizeof(int)); if(array == NULL) { printf("Can't get memory for that many values"); exit(EXIT_FAILURE); } /*读入数据*/ for( i = 0; i < n_values; i++) { printf("? "); if (scanf("%d",array + i) != 1) { printf("Error in reading value #%d\n",i); free(array); exit(EXIT_FAILURE); } } /*调用排序*/ qsort(array, n_values, sizeof(int), compare_integers); /*打印输出*/ for( i=0; i < n_values; i += 1) printf("%d\n",array[i]); free(array); return EXIT_SUCCESS; return 0; }
/* EXample 2: 用动态分配内存制作一个字符串的一份拷贝。 *注意:调用程序应该负责检查这块枫存是否成功分配! *这样做允许调用程序以任何它所希望的方式对错误作出反应。 */ #include <stdio.h> #include <stdlib.h> char *strdup( char const *string) { char *new_string; /*+1是为了考虑结尾的NUL字节*/ new_string = malloc(strlen(string) + 1); if ( new_string != NULL) strcpy(new_string, string); return new_string; }