c——内存管理

alloc

void *
     malloc(size_t size);
void *
     calloc(size_t count, size_t size);
void *
     realloc(void *ptr, size_t size);
解释:
  • calloc基本等同于malloc(count * size_t),but allocated memory filled with bytes of value zero
  • realloc tries to change the size of the allocation pointed to by ptr to size,返回的pointer可能等于ptr(在ptr指向的原有memory上change),也可能不等于ptr(create a new allocation),create a new allocation时,会copy ptr指向的原有memory中data到new allocated memory,并free ptr指向的原有memory
  • realloc第一个参数ptr为NULL时,realloc等同于malloc(size)
char* p1 = malloc(800);
char* p2 = realloc(p1, 500);
printf("p1 = %p, p2 = %p\n", p1, p2);
    
char* p3 = malloc(500);
char* p4 = realloc(p3, 1000);
printf("p3 = %p, p4 = %p\n", p3, p4);
    
free(p2);
free(p4);
output:
p1 = 0x100102d50, p2 = 0x100102d50
p3 = 0x100103070, p4 = 0x100103420
注意:不要释放p1和p3,实际运行p3可能等于p4,依赖运行时内存情况

free

void
     free(void *ptr);
if(p)
{
    free(p);
    p = NULL;
}
注:为防止野指针,记得指针值置NULL

你可能感兴趣的:(c)