- 指针在声明时要初始化,因为指针在创建的时候不会自动成为NULL,它缺省是随机的的一个地址(野指针)
- 当用malloc或new分配内存,应该判断内存是否分配成功,并初始化内存。
- 如果要用指针做为参数去分配一块内存,应该传递指针的指针或指针的引用。
- 指针在free()之后要指向NULL,不然它的值仍然会指向该内存。
如下指针s由于没有重置为NULL,它仍指向该内存。
#include <stdio.h> #include <stdlib.h> #include <string.h> void GetMem(char **p,int num) { *p=(char*)malloc(num); } int main() { char *s=NULL; GetMem(&s,100); strcpy(s,"hello"); printf("s previous is %s\n",s); free(s); if(s!=NULL) { strcpy(s,"world"); } printf("after free s is %s\n",s); return 0; }