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

             Bug #: 50501
           Summary: Insertion of complex into a stream may fail without
                    invalidating the stream
    Classification: Unclassified
           Product: gcc
           Version: 4.6.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
        AssignedTo: unassig...@gcc.gnu.org
        ReportedBy: giecr...@stegny.2a.pl
              Host: x86_64-suse-linux
            Target: x86_64-suse-linux
             Build: x86_64-suse-linux


I can see the following implementation in <complex>:

///  Insertion operator for complex values.
  template<typename _Tp, typename _CharT, class _Traits>
    basic_ostream<_CharT, _Traits>&
    operator<<(basic_ostream<_CharT, _Traits>& __os, const complex<_Tp>& __x)
    {
      basic_ostringstream<_CharT, _Traits> __s;
      __s.flags(__os.flags());
      __s.imbue(__os.getloc());
      __s.precision(__os.precision());
      __s << '(' << __x.real() << ',' << __x.imag() << ')'; // This can fail!
      return __os << __s.str(); // And then this may be empty!
    }

This implementation may cause the following test case to fail:

#include <cstdlib>
#include <cassert>
#include <iostream>
#include <complex>

int main () { float const a_f ((01));
    ::std:: complex < float > a_c ((a_f)); std:: stringstream a_s; 
    assert 
(!(a_s << a_c) || ((a_c = float ()) == float () && a_s >> a_c && a_c == a_f));
    return +EXIT_SUCCESS; }

I cannot reproduce the failure because I do not know how to inject a memory
allocation failure.  However, I imagine it is possible.

I suggest that the implementation be modified:

///  Insertion operator for complex values.
  template<typename _Tp, typename _CharT, class _Traits>
    basic_ostream<_CharT, _Traits>&
    operator<<(basic_ostream<_CharT, _Traits>& __os, const complex<_Tp>& __x)
    {
      basic_ostringstream<_CharT, _Traits> __s;
      __s.flags(__os.flags());
      __s.imbue(__os.getloc());
      __s.precision(__os.precision());
      __s << '(' << __x.real() << ',' << __x.imag() << ')';
      __os. setstate(__s.rdstate()) ;
      return __os << __s.str();
    }

Thank you for your consideration.

Reply via email to