【发布时间】:2010-11-13 04:51:25
【问题描述】:
我最近升级到 GCC 4.4(MinGW TDM 构建),现在下面的代码会产生这些警告:
在成员函数'void Console::print(const std::string&)'中:
警告:数组下标超出数组边界
代码如下:
void Console::print( const std::string& str ) {
std::string newLine( str );
if( newLine.size() > MAX_LINE_LENGTH ) {
sf::Uint32 stringSize = newLine.size();
for( sf::Uint32 insertPos = MAX_LINE_LENGTH;
insertPos < stringSize; insertPos += MAX_LINE_LENGTH ) {
newLine.insert( insertPos, "\n" );
}
}
StringList tokens;
boost::split( tokens, newLine, boost::is_any_of("\n") );
for( StringList::iterator it = tokens.begin();
it != tokens.end(); ++it ) {
addLine( *it );
}
}
有什么想法吗?
这是在做的优化......
这似乎是导致它的这条线:
boost::split( tokens, newLine, boost::is_any_of("\n") );
啊,是的,我找到了,它是 boost::is_any_of() 的参数,通过将它包装在 string() 构造函数中,警告消失了,谢谢大家的帮助:)
boost::split( tokens, newLine, boost::is_any_of( string( "\n" ) ) );
【问题讨论】:
-
大概编译器也给出了错误的行号?请通过评论在您的代码中注明。
-
出于好奇,如果您将
stringSize声明为const,它还会这样做吗? -
很明显,编译器正在尝试进行一些代码分析,以确定这种情况下的 for 循环是否可以让索引变量越界。我想知道它是否可能看到与索引变量进行比较的上限是非常量,并假设其他地方的一些其他代码可能会改变它(并且不够聪明,无法看到没有代码路径可以导致这里)。
-
鉴于你的编辑说它是哪一行,我对我的“编译器错误”理论更有信心。我认为它很可能是
boost::is_any_of,它正在遍历字符串文字并触发数组结尾指针的虚假绑定警告。 -
谢谢 - 我也有这个问题,你的解决方法帮助了我。赞成。