Josh Dybnis on 1 Oct 2003 04:42:59 -0000 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
Re: [ALACPP] Why won't g++ tell me I'm dumb? |
Technically gcc is doing the right thing here. String literals aren't actually constants. It's pretty obscure. I had to actually bust out the standard on this. What it says is that string literals are static arrays of type char, not const char. Attempting to modify a string literal is "undefined", but it's not actually forbidden for an implementation to support it. This is from the C standard, but I assume that C++ retains this for compatibility. -Josh --- Kevin Scaldeferri <kevin@xxxxxxxxxxxxxxx> wrote: > We had a bit of a puzzle at lunch today, trying to figure out why my > simple test case for my simple test function was dying a horrible > death. Here's the distilled version of the code: > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > #include <string.h> > > #include <boost/test/included/unit_test_framework.hpp> > using namespace boost::unit_test_framework; > > void strrev(char* s) { > int l = strlen(s); > char tmp; > int i; > > for ( i = 0 ; i < (l / 2) ; ++i ) { > tmp = s[i]; > s[i] = s[l - 1 - i]; > s[l - 1 - i] = tmp; > } > } > > void strrevtest() { > char* t; > t = ""; strrev(t);BOOST_CHECK_EQUAL( std::strcmp(t,""), 0); > t = "a"; strrev(t);BOOST_CHECK_EQUAL( std::strcmp(t,"a"), 0); > t = "ab"; strrev(t);BOOST_CHECK_EQUAL( std::strcmp(t,"ba"), 0); > t = "asdf"; strrev(t);BOOST_CHECK_EQUAL( std::strcmp(t,"fdsa"), > 0); > t = "asdfg"; strrev(t);BOOST_CHECK_EQUAL( std::strcmp(t,"gfdsa"), > 0); > } > > test_suite* > init_unit_test_suite ( int argc, char** argv) { > test_suite* test = BOOST_TEST_SUITE( "strrev test"); > test->add( BOOST_TEST_CASE( &strrevtest )); > return test; > } > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > This produces a memory access violation when it does the first swap. > > The reason is that I'm dumb and I was trying to modify a (const) > string > literal. Now, I can fix my test case by sticking in some strdup's, > but > there was also a consensus that the C++ compiler ought to complain. > However, it really seems to just silently discard the const-ness, > despite the suggestions of the g++ man page. > > Chris and I also tried with the Intel compiler, but that didn't > complain either. > > So, is there some flag we're missing that would spit out a warning > about this const issue? > > > > Kevin > > _______________________________________________ > alacpp mailing list > alacpp@xxxxxxxxxxx > http://lists.ellipsis.cx/mailman/listinfo/alacpp _______________________________________________ alacpp mailing list alacpp@xxxxxxxxxxx http://lists.ellipsis.cx/mailman/listinfo/alacpp