http://gcc.gnu.org/bugzilla/show_bug.cgi?id=46264
Summary: Trunk [4.6.0 20101028] - An overloaded operator returning rvalue reference invalidates stack. Product: gcc Version: unknown Status: UNCONFIRMED Severity: major Priority: P3 Component: c++ AssignedTo: unassig...@gcc.gnu.org ReportedBy: mirza.husad...@gmail.com Created attachment 22223 --> http://gcc.gnu.org/bugzilla/attachment.cgi?id=22223 ./dist/bin/g++ -v -std=c++0x -Wall -g -save-temps rvalue_bug.cpp The following code is compiled ('-std=c++0x -Wall -g') without optimizations. Sounds bizarre but the for loop (operator*) invalidates the stack, where invalid data pointer goes to delete (at the destructor) causing segmentation fault in libc.so. If the code is compiled without *for loop* there is no bug. Note: By compiling with optimization flags (-0, -O1, -O2, -O3) the bug can't be reproduced. #include <iostream> using namespace std; class foo { float *data; bool reused; public: foo() : data(new float), reused(false) { cout << "Allocating data: " << data << endl; } foo(foo&& f) : data(move(f.data)), reused(false) { f.data = NULL; cout << "Move constructor." << endl; } ~foo() { if(reused == false) { cout << "Deleting data: " << data << endl; delete data; }else cout << "Reused data: " << data << endl; } foo&& operator*(const foo& b) const { foo ab; int sum = 0; /// This for loop causes invalidation of stack. for(int i=0; i<0; i++) sum += i; ab.reused = true; cout << "Operator *. Sum: " << sum << endl; return move(ab); } }; int main() { foo a; foo b; foo c = a * b; return 0; }