[cfe-dev] c++11 and invalid opcode

Dimitry Andric dimitry at andric.com
Sun Feb 3 14:40:52 PST 2013


On 2013-02-03 23:24, Piotr MadaliƄski wrote:
> 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?

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.





More information about the cfe-dev mailing list