定义一个指针,一定要malloc才可以使用,不然就是野指针,无法使用?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
   char *p=NULL;
//   p=(char *)malloc(sizeof(p));  //注明此处没有申请内存,野指针,会出现内存泄漏。
   strcpy(p,"abc");
   printf("%s\n",p);
   return 0;

}

farsight@ubuntu:~/malloc$ gcc pp.c
farsight@ubuntu:~/malloc$ ./a.out
Segmentation fault (core dumped)

farsight@ubuntu:~/malloc$ 


申请内存才可以使用

farsight@ubuntu:~/malloc$ vi pp.c
farsight@ubuntu:~/malloc$ gcc pp.c
farsight@ubuntu:~/malloc$ ./a.out
abc
farsight@ubuntu:~/malloc$ 


猜你喜欢

转载自blog.csdn.net/Makefilehoon/article/details/80905692
今日推荐