Segmentation Fault when outputting in C++
<p>I am trying to print out an array of integers. I am getting a seg fault when I try to print as below. If I uncomment the "In for loop" it will print everything except the last item of the array and it still has a seg fault. When I uncomment both of the comments (or just the "done with for loop") everything prints fine. Why does this happen and how do I fix it?</p>

<pre><code>for( int i = 0; i &lt; l.usedLength; i++ )
{
    //cout &lt;&lt; "**********In for loop" &lt;&lt; endl;
    cout &lt;&lt; l.largeInt[ i ];
}
//cout &lt;&lt; "**********done with for loop" &lt;&lt; endl;
</code></pre>

<p>Here is the whole class:</p>

<pre><code>#include "LargeInt.h"
#include &lt;ctype.h&gt;

LargeInt::LargeInt()
{
    usedLength = 0;
    totalLength = 50;

    largeInt = new int[totalLength];
    for( int i=0; i&lt;totalLength; i++ )
    {
        largeInt[i] = 0;
    }
}

LargeInt LargeInt::operator+(const LargeInt &amp;l) const
{}

LargeInt LargeInt::operator-(const LargeInt &amp;l) const
{}

LargeInt LargeInt::operator*(const LargeInt &amp;l) const
{}

LargeInt LargeInt::operator/(const LargeInt &amp;l) const
{}

bool LargeInt::operator==(const LargeInt &amp;l) const
{}

ostream&amp; operator&lt;&lt;(ostream &amp;out, const LargeInt &amp;l)
{
    cout &lt;&lt; "In output" &lt;&lt; endl;

    if( l.usedLength == 0 )
    {
        cout &lt;&lt; 0;
    }
    else
    {
        cout &lt;&lt; "In else... NON 0" &lt;&lt; endl;

        for( int i = 0; i &lt; l.usedLength; i++ )
        {
            cout &lt;&lt; "In for loop" &lt;&lt; endl;
            cout &lt;&lt; l.largeInt[ i ];
        }
        //cout &lt;&lt; "done with for loop" &lt;&lt; endl;
    }
    //cout &lt;&lt; "after the if.... all done with output" &lt;&lt; endl;
}

istream&amp; operator&gt;&gt;(istream &amp;in, LargeInt &amp;l)
{
    char x;
    while (std::cin.get(x) &amp;&amp; x &gt;= '0' &amp;&amp; x &lt;= '9')
    {
        l.largeInt[ l.usedLength ] = x-48;
        l.usedLength++;
        //need to check array length and make bigger if needed
    }

}
</code></pre>

<p>Main:</p>

<pre><code>#include &lt;stdlib.h&gt;
#include &lt;iostream&gt;

#include "LargeInt.h"

int main(int argc, char** argv) {

    cout &lt;&lt; "\nJosh Curren's Assignment #5 - Large Integer\n" &lt;&lt; endl;

    LargeInt lint;

    cout &lt;&lt; "Enter a large int: ";
    cin &gt;&gt; lint;

    cout &lt;&lt; "\nYou entered: " &lt;&lt; endl;
    cout &lt;&lt; lint &lt;&lt; endl;
    cout &lt;&lt; endl;


    return (EXIT_SUCCESS);
}
</code></pre>
