mystery segmentation fault involving template

Discussion in 'C++' started by nandor.sieben@gmail.com, Mar 14, 2008.

  1. Guest

    The following program causes a segmentation fault. If I break the
    print line at the end into two separate print statement then there is
    no segmentation fault. What is the problem? I am compiling it on
    Ubuntu Gutsy.

    using namespace
    std;

    #include
    <iostream>
    #include
    <sstream>

    template < class T > string all2string (T in, int
    i)
    {
    stringstream
    s;
    s <<
    in;
    string
    ss;
    ss = s.str
    ();
    while (ss.length () <
    i)
    ss = "0" +
    ss;
    return
    ss;
    }

    typedef
    struct
    {
    int
    move;
    int
    depth;
    }
    Tdata;

    string
    Tdata2string (const Tdata &
    data)
    {
    string s
    =
    all2string (data.depth, 0) + " " + all2string (data.move, 0) + "
    ";
    return
    s;
    }

    ostream & operator << (ostream & os, const Tdata &
    data)
    {
    string s = Tdata2string
    (data);
    os <<
    s;
    }

    main
    ()
    {
    Tdata
    dat;
    dat.depth =
    0;
    dat.move =
    -1;


    cout << dat <<"data
    \n";
    }
     
    , Mar 14, 2008
    #1
    1. Advertising

  2. Greg Herlihy Guest

    On Mar 14, 11:58 am, wrote:
    > The following program causes a segmentation fault. If I break the
    > print line at the end into two separate print statement then there is
    > no segmentation fault. What is the problem? I am compiling it on
    > Ubuntu Gutsy.
    >

    ...

    .
    > ostream & operator <<(ostream& os, const Tdata& data)
    > {
    >   string s = Tdata2string(data);
    >   os << s;
    > }


    The last line of your operator<<() routine (above) should be

    return os << s;

    Greg
     
    Greg Herlihy, Mar 14, 2008
    #2
    1. Advertising

  3. Guest

    > The last line of your operator<<() routine (above) should be
    >
    >     return os << s;
    >
    > Greg


    It works, thank you very much.
     
    , Mar 14, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Alex Hunsley
    Replies:
    17
    Views:
    894
  2. Pud
    Replies:
    0
    Views:
    606
  3. darkstorm
    Replies:
    1
    Views:
    399
    Victor Bazarov
    Apr 27, 2005
  4. er
    Replies:
    5
    Views:
    513
    James Kanze
    Feb 13, 2008
  5. Jim Huskey
    Replies:
    1
    Views:
    124
    Michael Baltic
    Jun 29, 2005
Loading...

Share This Page