malloc 需要注意的事项

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 void getmemory(char *p)
 5 {
 6         p=(char *) malloc(100);
 7         strcpy(p,"hello world");
 8 }
 9 
10 
11 int main()
12 {
13         char *str=NULL;
14        // str=(char*)malloc(100);    //应该在此处分配空间
15         getmemory(str);
16         printf("%s\n",str);
17 
18         free(str);
19         return 0;
20 }

此段程序的目的是在main中定义一个char指针ptr,并将其传入getmemory函数中,传入后,希望分配空间并copy一个字符窜到str中,然后main函数将此字符串输出。

程序的问题在于,malloc在getmemory函数中分配,在这里分配的是为临时分配,当函数结束后分配的空间将无法找到,虽然没有释放掉内存,因此,运行时出现段错误。

posted @ 2015-06-04 16:33  道心不可练  阅读(250)  评论(7编辑  收藏  举报