#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;
#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$
本文通过一个简单的C语言程序示例,展示了未正确初始化的指针(即野指针)在尝试使用时可能导致程序崩溃的情况,并对比了正确申请内存后的程序运行结果,强调了在C/C++中合理管理内存的重要性。
607

被折叠的 条评论
为什么被折叠?



