Random characters displayed when printing array of characters
<p>This is my problem. I am reading a file in binary mode, appending the bytes to an int array, and printing the values after. My problem is, when I cout my results, random characters are being attached in the stream.</p>

<p>comp.txt:</p>

<pre><code>this text is a testt1
</code></pre>

<p>main.cpp:</p>

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


using namespace std;

void read(ifstream&amp; stream, unsigned int buf[], int size)
{
    for(int i = 0; i &lt; size; ++i)
    {
        unsigned char temp[4] = {'\0', '\0', '\0', '\0'};
        stream.read((char*)temp, 4);
        cout &lt;&lt; "Temp: " &lt;&lt; temp &lt;&lt; '\n';
        buf[i] = *((int*)temp);     
        cout &lt;&lt; "Read: " &lt;&lt; buf[i] &lt;&lt; endl;
        memset(temp, '\0', 4);
    }
}

int main()
{

    // open file
    ifstream f;
    f.open("comp.txt", ios::binary);
    cout &lt;&lt; "File opened. " &lt;&lt; endl;

    // get size
    f.seekg(0, ios::end);
    int l = f.tellg();
    int length = (l / 4) + 1;
    f.seekg(0, ios::beg);
    cout &lt;&lt; "Size found: L: " &lt;&lt; l &lt;&lt; " Length: " &lt;&lt; length &lt;&lt; endl;

    // allocate byte arrays
    unsigned int* buf = new unsigned int[length];
    memset(buf, '\0', 4*length);
    // unsigned short* key = new unsigned short[length];
    cout &lt;&lt; "Preparing to read..." &lt;&lt; endl;

    // read byte into short
    cout &lt;&lt; "Reading..." &lt;&lt; endl;
    read(f, buf, length);
    f.close();
    delete[] buf;
    cin.ignore(1000, 10);
    return 0;
}
</code></pre>

<p>Output:</p>

<pre><code>C:\Users\daminkz\Desktop&gt;encrypt
File opened.
Size found: L: 21 Length: 6
Preparing to read...
Reading...
Temp: this
Read: 1936287860
Temp:  tex☺
Read: 2019914784
Temp: t is☻
Read: 1936269428
Temp:  a t♥
Read: 1948279072
Temp: estt♦
Read: 1953788773
Temp: 1
Read: 49
</code></pre>

<p>Things to note:</p>

<ul>
<li>temp is only 4 bytes, but 5 bytes are printed</li>
</ul>
