0
点赞
收藏
分享

微信扫一扫

malloc带来的一些问题

一:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>


void get_memory(char *p)
{
p = (char *)malloc(100);
if(p == NULL){
printf("aaaaaaaaaaa\n");
}
}


int
main(int argc, char *argv[])
{
char *str = NULL;
get_memory(str);

if(str == NULL){
printf("bbbbbbbbbbb\n");
}
strcpy(str, "hello world");

printf("%s\n", str);
exit(0);
}

输出:段错误
原因:str  的值没有该变,还是为NULL,光改变 p  的值没啥用

二:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

char *get_memory(void)
{
char p[20] = {"hello world"};
return p;
}

int
main(int argc, char *argv[])
{
char *str = NULL;
str = get_memory();

if(str == NULL){
printf("bbbbbbbbbbb\n");
}

printf("%s\n", str);
exit(0);
}

输出:无现象

原因:

 

三:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

void get_memory(char **p, int num)
{
*p = (char *)malloc(num);
if(p == NULL){
printf("aaaaaaaaaaa\n");
}
}


int
main(int argc, char *argv[])
{
char *str = NULL;
get_memory(&str, 100);

if(str == NULL){
printf("bbbbbbbbbbb\n");
}
strcpy(str, "hello world");

printf("%s\n", str);
exit(0);
}

输出:hello world
原因:str的值改变了,所以输出了

 

四:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

int
main(int argc, char *argv[])
{
char *str = (char *)malloc(100);

strcpy(str, "hello");
printf("%s, addr = %d\n", str, (int)str);

free(str);
if(str != NULL){
strcpy(str, "world");
printf("%s, addr = %d\n", str, (int)str);
}

exit(0);
}

输出:
hello, addr = 16064528
world, addr = 16064528
原因:free并不能改变str的值,只能释放空间,地址值还在

 

 

 

 

 


举报

相关推荐

0 条评论