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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值