- 论坛徽章:
- 0
|
- void getmemory1(char *p)
- {
- p = (char *)malloc(100);
- }
- void test1(void)
- {
- char *str = NULL;
- getmemory1(str);
- strcpy(str, "hello world");
- cout<< str << endl;
- }
复制代码
strcpy(str, "hello world");把"hello world"copy到一个NULL指针,然后你的代码被OS咔嚓,还丢了100字节的内存,因为getmemory1压根就不能分配内存给str:getmemory1给参数p的副本--函数体里的p分配了内存,没参数p毛事。
- void getmemory2(char **p, int num)
- {
- *p = (char *)malloc(num);
- }
- void test2(void)
- {
- char *str = NULL;
- getmemory2(&str, 100);
- strcpy(str, "hello");
- cout<< str << endl;
- }
复制代码
感觉上一个无厘头吗?这个才无厘头!没free!够无厘头吧?
- char *getstring(void)
- {
- char *p = "hello world";
- return p;
- }
- void test3(void)
- {
- char *str = NULL;
- str = getstring();
- cout<< str << endl;
- }
复制代码
为什么无厘头?因为只能得到一个只读的"hello world"! |
|