int_to_str函数的坑

来看看下面这个函数

/*将int 变换为字符串的程序*/
char *int_to_str(int int_value){
	char buf[20];
	sprintf_s(buf, "%d", int_value);
	return buf;
}

当我们运行这个程序的时候,会报警告。


在vs2013的编译环境中,这样并不会导致程序崩溃,只会提出一个警告。在函数buf是个局部变量,当函数运行完成,该内存区域就会被释放。那么,返回的时候,我们无法找到buf的地址。但由于现在的编译器的容错性越来越高,所以有些错误编译器是可以忽略的。


当我们将上述函数改写为如下形式

char *int_to_str(int int_value){
	static char buf[20]
	sprintf_s(buf, "%d", int_value);
	return buf;
}

当我们将buf变量声明为static的时候,buf的内存区域一直会被静态地保持。即使函数执行结束,buf的内存区域也不会被释放。当我们return的时候,也就能找到地址了。

 

但是当我们改为第二形式的时候,我们两次调用int_to_str函数的时候,返回的结果都是第二次的值。因为在我们使用static变量的时候,这块内存已经被划分了,所有当我们调用这个函数多次的时候,也只是在对这块内存进行修改。所以,得到的结果永远是第二次的值。

 

于是我们考虑使用malloc函数。代码如下:

#include "stdio.h"
#include "malloc.h"

char *int_to_str(int int_value){
	char* buf = (char *)malloc(sizeof(char)* 20);
	sprintf_s(buf,20,"%d",int_value);
	return buf;
}
int _tmain(int argc, _TCHAR* argv[])
{
	char *s1=int_to_str(10);
	char *s2 = int_to_str(20);
	printf("%s,%s", s1,s2);	
	/*printf("%s", s1);
	char *s2 = int_to_str(20);
	printf("%s", s2);*/
	return 0;
}


通过调试,我们发现malloc每次分配的内存是不一样。所以能够愉快的满足我们的需求。但是我并没有找到比较好的方式free掉malloc的内存。于是我只能采用下一种方式。使用数组接收参数。

#include "stdafx.h"
#include "stdio.h"

int int_to_str(int int_value,char buf[20]){
	sprintf_s(buf,20,"%d",int_value);
	return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
	char s1[20];
	char s2[20];
	int_to_str(10, s1);
	int_to_str(20, s2);
	printf("%s,%s", s1,s2);
	/*printf("%s", s1);
	char *s2 = int_to_str(20);
	printf("%s", s2);*/
	return 0;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值