哈喽,大家好!最近在循环处理文件的时候遇到了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));
}