内存管理malloc 2

malloc可以在函数指针内使用。

#include <stdio.h> #include <stdlib.h> char * get_string() { //char s[] = "welcome"; //(有警告)局部变量,放在栈上,函数结束自动销毁 //static char s[] = "welcome"; //静态存储区,从分配开始,到程序结束才被回收。 //char *s = "welcome"; //指针,字符串常量,不允许修改。 char * s; s = (char *)malloc(10*sizeof(char)); if(s == NULL) { printf("malloc failed\n"); return 0; } printf("input:"); scanf("%s",s); printf("%s\n",s); return s; //要保证返回的地址能被主函数正常接收到 } int main(int argc, const char *argv[]) { char *p; p = get_string(); printf("%s\n",p); free(p); p = NULL; return 0; }

  注意这个地方那就是malloc返回一个p指针。

 p指针=“ssss”; 这个时候相当于将字符串的常量指针返回给了P指针了。这时候free释放的指针就会出现错误的。

 

posted @ 2018-12-11 09:03  jack_hzm  阅读(233)  评论(0编辑  收藏  举报