C++ GCC4.4 warning: array subscript is above array bounds

我们两清 提交于 2019-12-04 20:05:25

问题


I recently upgraded to GCC 4.4 (MinGW TDM build) and now the follow code produces these warning:

In member function 'void Console::print(const std::string&)':

warning: array subscript is above array bounds

Here's the code:

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 );
        }
    }

Any ideas?


It is the optimizations that are doing it...

Also it appears to be this line which is causing it:

boost::split( tokens, newLine, boost::is_any_of("\n") );

Ah yes, I found it, it is the argument for boost::is_any_of(), by wrapping it in a string() constructor the warning goes away, thank you all for your help :)

boost::split( tokens, newLine, boost::is_any_of( string( "\n" ) ) );

回答1:


Got the same error. As a workaround I replaced

is_any_of(" ")

with

is_from_range(' ', ' ')

which might also be slightly more efficient.




回答2:


Could have something to do with one or more of these GCC bugs:

GCC bugzilla search results for "Warning: array subscript is above array bounds"

Not all of them are valid, but there are some fixed ones if you search around, too:

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37861

So I'm pretty sure there's something going on there. Based on the comments, I'd try compiling without optimisation and see if it goes away.

I got a spurious bounds warning using one of the standard algorithms (std::remove, I think) and passing iterator parameters:

myarray, 
myarray + sizeof(myarray)/sizeof(*myarray)

which I'm pretty sure are in bounds. It was only in toy code, though, so I just bodged around it. If GCC really is throwing dodgy warnings you'll just have to inspect your code extra-carefully until it's fixed.




回答3:


I notice your loop here is altering the length of the string, but not updating the loop termination condition. Could this be the source of your issue?

   sf::Uint32 stringSize = newLine.size();
   for( sf::Uint32 insertPos = MAX_LINE_LENGTH;
      insertPos < stringSize; insertPos += MAX_LINE_LENGTH ) 
   {
      newLine.insert( insertPos, "\n" );
      // You were probably wanting to put this here..
      insertPos++;
      stringSize++;
   }


来源:https://stackoverflow.com/questions/1168525/c-gcc4-4-warning-array-subscript-is-above-array-bounds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!