再谈 char a[] 与 char *p
//错误void GetMemory(char *p){ p = malloc(100);}//可以正确返回char * GetMemory(void){ char p[] = "hello world"; return p;}//错误char * GetMemory(void){ char *p = "hello world"; return p;}
void GetMemory(char **p){ *p = (char*)malloc(100);}
[解决办法]
malloc函数返回类型是void*型,所以你要强制类型转换。
[解决办法]
这个是不可以的,因为这个相当于从静态区COPY了一份到栈上,函数退出时,栈上的那个就无意义了
char * GetMemory(void){ char p[] = "hello world"; return p;}而下面这个是可以的。。。
[解决办法]
//这个不会自动释放内存的,长时间频繁调用肯定造成把内存耗死,
void GetMemory(char *p)
{
p = malloc(100);
}
//这个 "hello world";放在栈里,如果多线程的话,可能会被其他函数给覆盖了,所以这个也是NG的
char * GetMemory(void)
{
char p[] = "hello world";
return p;
}
//这个是可以的,但是返回 "hello world"是只读的,不能修改的!
char * GetMemory(void)
{
char *p = "hello world";
return p;
}
[解决办法]
仍然不行,函数结束后,a所指向的内存单元即数组P已经释放,因为P是自动变量!(当然你这样也有可能得到正确的结果,前提是该段内存单元没有被其它变量占用)
char * GetMemory(void){ char p[] = "hello world"; return p;}
[解决办法]
void GetMemory(char *p){ p = (char *)malloc(100);}void Test(void){ char *str = NULL; GetMemory(str); strcpy(str, "hello world"); printf(str);}//请问运行Test 函数会有什么样的结果?//答:程序崩溃。//因为GetMemory 并不能传递动态内存,Test 函数中的 str 一直都是 NULL。strcpy(str, "hello world");将使程序崩溃。char *GetMemory(void){ char p[] = "hello world"; return p;}void Test(void){ char *str = NULL; str = GetMemory(); printf(str);}//请问运行Test 函数会有什么样的结果?//答:可能是乱码。//因为GetMemory 返回的是指向“栈内存”的指针,该指针的地址不是 NULL,但其原先的内容已经被清//除,//新内容不可知。void GetMemory2(char **p, int num){ *p = (char *)malloc(num);}void Test(void){ char *str = NULL; GetMemory(&str, 100); strcpy(str, "hello"); printf(str);}//请问运行Test 函数会有什么样的结果?//答:(1)能够输出hello;(2)内存泄漏void Test(void){ char *str = (char *) malloc(100); strcpy(str, “hello”); free(str); if(str != NULL) { strcpy(str, “world”); printf(str); }}//请问运行Test 函数会有什么样的结果?//答:篡改动态内存区的内容,后果难以预料,非常危险。//因为free(str);之后,str成为野指针,if(str != NULL)语句不起作用。