关于申请内存的问题,我也很头疼,每次报错不知道为什么,一个一个来吧!
1.用把malloc不放在自己定义的函数里面,编译报错,放到自己定义的函数里面,编译通过,不知道为什么!
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void fun(char *p)
{
p=(char *)malloc(100);
free(p);
}
int main()
{
char *p=(char *)malloc(100);
char *str=NULL;
fun(str);
// str=p;
strcpy(str,"Hello world");
printf("%s\n",str);
return 0;
}
结果:
liuzj@ET302Buildver:~/zhanghong/king/20180222$ vim free.c
liuzj@ET302Buildver:~/zhanghong/king/20180222$ gcc free.c
liuzj@ET302Buildver:~/zhanghong/king/20180222$ ./a.out
段错误 (核心已转储)
liuzj@ET302Buildver:~/zhanghong/king/20180222$
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/*
void fun(char *p)
{
p=(char *)malloc(100);
free(p);
}
*/
int main()
{
char *p=(char *)malloc(100);
char *str=NULL;
// fun(str);
str=p;
strcpy(str,"Hello world");
printf("%s\n",str);
return 0;
}
~
liuzj@ET302Buildver:~/zhanghong/king/20180222$ gcc free.c
liuzj@ET302Buildver:~/zhanghong/king/20180222$ ./a.out
Hello world
liuzj@ET302Buildver:~/zhanghong/king/20180222$
2.在其他函数中申请的局部变量,函数执行完后就释放了,不存在了,不可以作为返回值。
#include<stdio.h>
char *fun1(void)
{
char p[]="hello world";
return p;
}
int main(void)
{
char *str=NULL;
str=fun1();
printf("%s\n",str);
return 0;
}
结果:
存储在stack中,但是stack中的变量在完成function之后会自动释放,所以也会返回一个野指针
liuzj@ET302Buildver:~/zhanghong/king/20180222$ gcc free1.c
free1.c: In function ‘fun1’:
free1.c:5:4: warning: function returns address of local variable [-Wreturn-local-addr]
return p; //P这个变量不存在
3.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void fun(char **p,int num)
{
*p=(char *)malloc(num);
}
int main()
{
char *str=NULL;
fun(&str,100);
strcpy(str,"hello");
printf("%s\n",str);
return 0;
}
liuzj@ET302Buildver:~/zhanghong/king/20180222$ vim malloc.c
liuzj@ET302Buildver:~/zhanghong/king/20180222$ gcc malloc.c
liuzj@ET302Buildver:~/zhanghong/king/20180222$ ./a.out
hello //不知道为什么打印hello
4.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *str=(char *)malloc(100);
strcpy(str,"hello");
free(str);
if(str!=NULL)
{
strcpy(str,"world");
}
printf("%s\n",str);
return 0;
}
liuzj@ET302Buildver:~/zhanghong/king/20180222$ vim world.c
liuzj@ET302Buildver:~/zhanghong/king/20180222$ gcc world.c
liuzj@ET302Buildver:~/zhanghong/king/20180222$ ./a.out
world
liuzj@ET302Buildver:~/zhanghong/king/20180222$