用malloc开辟了一块内存空间,但没有free,没有显示内存泄漏,为什么? #include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
int main()
{
char *p=NULL;
p=(char*)malloc(100);
strcpy(p,"hello world!");
printf("%s\n",p);
return 0;
}
liuzj@ET302Buildver:~/zhanghong/king/2018125$ g++ neicun1.cpp
liuzj@ET302Buildver:~/zhanghong/king/2018125$ ./a.out
hello world!
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
int main()
{
char *p=NULL;
p=(char*)malloc(100);
strcpy(p,"hello world!");
printf("%s\n",p);
return 0;
}
liuzj@ET302Buildver:~/zhanghong/king/2018125$ g++ neicun1.cpp
liuzj@ET302Buildver:~/zhanghong/king/2018125$ ./a.out
hello world!
liuzj@ET302Buildver:~/zhanghong/king/2018125$
但是这样做却会报错,为什么?
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
void fun(char *p)
{
p=(char *)malloc(100);
}
int main()
{
char *p=NULL;
// p=(char*)malloc(100);
char *str=NULL;
fun(str);
strcpy(str,"hello world!");
printf("%s\n",str);
// free(str);
return 0;
}