57 การปลดหน่วยความจำ ( free )


  • ทุกครั้งที่ทำการใช้ malloc หรือ realloc ควรทำการ fee ทุกครั้ง เพื่อป้องกันหน่วยความจำรั่ว ( memory leak )

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char str[] = "123456";
char *p = NULL;
p = (char *) realloc(p,strlen(str) + 1);
if(p == NULL) exit(-1);
strcpy(p,str);
p = (char *) realloc(p,strlen(p) + strlen(str) + 1);
if(p == NULL) exit(-1);
strcat(p,str);
printf("%s",p);
free(p);
return 0;
}