对于我正在编写的程序,计算文件大小对我很有用,我使用 iostream 的 tellg 和 seekg 函数来计算,但这会导致 -Wstack-protector 发出警告。以下代码重现了“问题”:
#include <iostream>
std::streamsize get_file_size(std::ifstream& ifs) { // line 12 (in warning, below)
const std::streamsize start = ifs.tellg();
ifs.seekg(0,std::ios::end);
const std::streamsize end = ifs.tellg();
ifs.seekg(start);
return (end-start);
}
g++(标志:-fstack-protector -Wstack-protector,编译器版本:4.4.3(Ubuntu 4.4.3-4ubuntu5),系统:Ubuntu 10.04 x86_64)给出警告:
f.cc:在函数'std::streamsize get_file_size(std::ifstream&)'中:
f.cc:12:警告:不保护函数:没有至少 8 字节长的缓冲区
(当我使用直接从 GNU 下载和编译的 GCC 4.5.2 时,我得到了相同的结果。)
这是从堆栈粉碎保护的工作方式(通常或通过 GCC)和/或 ifstream 和 seekg/tellg 的工作方式中预期的吗?如果是这样,这个警告不能被忽略还是有更好的办法吗?
编辑:
实际上,上面的一些代码是多余的。只是为了澄清发生了什么:
#include <iostream>
void f1(std::ifstream& ifs) { // line 6
ifs.tellg();
}
void f2(std::ifstream& ifs) { // line 10
// call seekg(std::streampos)
ifs.seekg(0);
}
void f3(std::ifstream& ifs) {
// call seekg(std::streamoff, std::ios_base::seekdir)
ifs.seekg(0,std::ios::beg);
}
导致 g++(与上述相同的规格)警告:
main.cc:在函数 'void f1(std::ifstream&)' 中:
main.cc:6:警告:不保护函数:没有至少 8 字节长的缓冲区
main.cc:在函数 'void f2(std::ifstream& )':
main.cc:10: 警告:没有保护功能:没有至少 8 字节长的缓冲区
有趣的是,f3
不会触发警告。