c++11 and invalid opcode

Hi everybody,

I'm trying to compile this code:

#include <iostream>
#include <future>
#include <string>
#include <algorithm>

using namespace std;

string flip(string s) {
    reverse(s.begin(),s.end());
    return s;
}

int main()
{
        vector<future<string>> v;
        v.push_back(async((){ return flip(" olleH"); }));
        v.push_back(async((){ return flip("\n!dlroW"); }));
        for(auto &a : v) {
                cout << a.get();
        }
}

It runs fine when compiled with gcc with the following comand:

g++ -std=c++11 -pthread main.cpp -o main

But when I switch to clang:

clang++ -std=c++11 -pthread main.cpp -o main

It segfaults printing out 'Illegal instruction'

In addition this error ends up in the logs:

kernel: [ 4646.986707] main[2502] trap invalid opcode ip:409f87 sp:7fff7a47c5b0 error:0 in main[400000+1a000]

I'm running clang 3.3 from SVN on Linux x86_64 (ArchLinux).

So what exactly did I mess up?

Regards,
Peter

Your flip() function is causing undefined behaviour, as string::end()
returns an iterator to the character *following* the last character of
the string. Dereferencing that iterator is not allowed, you can only
compare it against other iterators.

Your flip() function is causing undefined behaviour, as string::end()
returns an iterator to the character *following* the last character of
the string. Dereferencing that iterator is not allowed, you can only
compare it against other iterators.

Where exactly does it dereference the off-the-end iterator?
std::reverse takes a half-open range.

-- Sean Silva

Right. I think, that the code is correct.
The issue is probably some ABI-related problem on my machine.