在内存申请和使用上总是会出现一些莫名其妙的问题,今天刚好又碰到了,这里总结一下。
//1.编译可以通过,但是执行不过。卡死在注释那一句void test(){ char * str = (char *)malloc(100); strcpy(str,"hello"); free(str); if(str != NULL) { strcpy(str,"world"); printf("%s\n",str);//因为str已经free,所以对str的访问出现问题,卡死在这一步 }}//---------------------------------------//2.双指针是OK的void getMemory(char **p,int num){ *p = (char *)malloc(num);}void test(){ char *str = NULL; getMemory(&str,100); strcpy(str,"hello"); printf("%s\n",str);}//-----------------------------------------//3.编译通过,执行通过,返回垃圾文字。char * getmemory(){ char p[] = "hello world"; return p;}void test(){ char *str = NULL; str = getmemory(); printf("%s\n", str);//因为getmemory()中返回的是局部变量的地址, //所以在getmemory()执行完毕后,该变量自动释放。所以访问失败。输出一些垃圾文字。}//-----------------------------------------//4.编译通过,执行失败。void getmemory(char *p){ p = (char *)malloc(100);//内存空间申请后,指向这一空间的指针被释放}void test(){ char *str = NULL; getmemory(str); strcpy(str, "hello world");//str没有空间来容纳后面的字符串 printf("%s\n", str);}