内存管理
内存管理之简单内存分配
标准C语言函数库malloc函数
#include <stdio.h>
void *malloc(size_t size);
测试代码:
/*mempty_malloc.c*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#define MALLOC_SIZE (1024)
int main()
{
char *malloc_memory;
int mallocSize;
int exitStat;
mallocSize = MALLOC_SIZE;
exitStat = EXIT_FAILURE;
malloc_memory = (char *)malloc(mallocSize);
if(malloc_memory != NULL)
{
sprintf(malloc_memory,"Memory Malloc Test!\n");
printf("value = %s \n",malloc_memory);
exitStat = EXIT_SUCCESS;
}
return 0;
}
- malloc函数返回的是 void * 指针,需要强制转换成需要的类型(如:char *)。
- malloc函数返回的内存地址是对齐的,故可以被转换为任何类型的指针。
内存管理之释放内存
#include <stdlib.h>
void free(void *ptr_to memory);
该函数使用的指针参数必须指向由malloc、calloc、realoc函数所申请的内存。
/*free_memory.c*/
#include <stdlib.h>
#include <stdio.h>
#define MEMORY_SIZE (1024)
int main()
{
char *newMemory;
int exitStat = EXIT_FAILURE;
newMemory = (char *)malloc(MEMORY_SIZE);
if(newMemory != NULL)
{
free(newMemory);
printf("Memory Test : malloc and free \n");
exitStat = EXIT_SUCCESS;
}
return 0;
}
内存被free后,就不能够对其进行相关操作。
内存管理之calloc 与 realloc
#include <stdlib.h>
void *calloc(size_t number_of_elments, size_t element_size);
void *realloc(void *existing_memory, size_t new_size);
calloc函数:为一个结构数组非农配内存,分配的内存将被初始化为0,使用free进行内存释放。
calloc参数:申请元素个数、每个元素大小。
realloc函数:改变之前已分配内存的长度,根据new_size参数值增加或减少长度。当内存被重新分配之后,必须使用新指针去访问内存。如果无法调整内存块大小,将返回NULL指针。
realloc参数:先前已分配的内存指针、需增加或减少的长度。
注:
若realloc调用失败,将返回空指针,之前分配的内存将无法在通过原指针访问,故在释放旧内存之前,先malloc申请新空间,并把数据memcpy到新空间,在进行realloc调用。