2020-12-28

哈喽,大家好!最近在循环处理文件的时候遇到了W2A导致堆栈溢出的问题,跟大家简单交流下。

1、起因是需要对几万张.raw文件进行批量处理,所以用到了CFileFind类和fopen等函数,中间就涉及到路径的问题,CString转const char*,最简单便捷的就是W2A了;

2、首先USES_CONVERSION宏定义所使用的内存是通过函数alloca分配的,而alloca的内存是在栈空间内部分配,VC的编译器默认的编译空间为2M。故W2A使用alloca在栈上分配内存,退出生命周期后才会释放所占用的内存。所以在一个函数的循环体中使用W2A等字符转换宏可能引起栈溢出。

3、解决方案:最简单的就是在使用的时候自己写函数对W2A进行封装,这样在函数返回时,栈内存已经释放,问题就可以得到解决。

贴段代码(减部分):                     

bfinder2 = finder2.FindFile(finder1.GetFilePath() + L"\\*.*");
while (bfinder2)
{
	bfinder2 = finder2.FindNextFile();
	if (finder2.IsDots())
		continue;
	else if (finder2.IsDirectory())
	{
		if (finder2.GetFileName().Right(5) == L"tsoff")
		{
			path_offsetnor = finder2.GetFilePath() + L"\\nor\\tmp_offset_1.raw";
			path_offsetcold = finder2.GetFilePath() + L"\\cold\\tmp_offset_1.raw";
			CString2char(path_offsetnor, szRawFile);
			f = fopen(szRawFile, "rb");
			if (f)
			{
				fread(offset_nor, 1, frameLong, f);
				fclose(f);
			}

			CString2char(path_offsetcold, szRawFile);
			f = fopen(szRawFile, "rb");
			if (f)
			{
				fread(offset_cold, 1, frameLong, f);
				fclose(f);
			}
		}
	}
} 

//自己写函数重新封装W2A
void CString2char(CString str, char* path)
{
	USES_CONVERSION;
	memset(path, 0, 1024);
	strcpy(path, W2A(str));
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值