问题描述
Visual Studio 2022编写一个readAll函数用于读取文件,但是在Debug版本下有乱码,但是切换到Release版本,一切都变得正常。
const char* readAll(const char* filename) {
std::ifstream is(filename, std::ios::in);
is.seekg(0, std::ios::end);
std::size_t size = (int)is.tellg();
is.seekg(0, std::ios::beg);
char* data = new char[size];
is.read(data, size);
is.close();
return data;
}
原因分析:
通过搜索,我发现在Release版本下的未初始化变量都会初始化为0。
解决方案:
在创建字符数组时,进行初始化,防止乱码
const char* readAll(const char* filename) {
std::ifstream is(filename, std::ios::in);
is.seekg(0, std::ios::end);
std::size_t size = (int)is.tellg();
is.seekg(0, std::ios::beg);
char* data = new char[size]{0}; // changed
is.read(data, size);
is.close();
return data;
}