C++ error: terminate called after throwing an instance of 'std::bad_alloc'
<p>I wrote the code pasted below to perform the following tasks in the order in which they are stated: </p>

<ol>
<li>Read an input file and count the number of entries in it</li>
<li>Create an array of appropriate size (size equal to number of entries)</li>
<li>Go back to the beginning of the input file and read it again</li>
<li>Store the entries in an array</li>
<li>Print out the number of entries in the file and the entries themselves.</li>
</ol>

<p>Here is my code:</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;exception&gt;

using namespace std;

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

    ifstream inFile(argv[1]); //passing arguments to the main function
    int numEntries;

    if(!inFile){
        cout &lt;&lt; "file not found" &lt;&lt; endl;
        return 1;
    }

    string entry;
    while (!inFile.eof()){ //counting the number of entries
        getline(inFile,entry);
        ++numEntries;
    }

    const int length = numEntries;  //making an array of appropriate length
    int*arr = new int[length];

    inFile.clear();             //going back to the beginning of the file
    inFile.seekg(0, ios::beg);

    int i = 0;
    const int size = numEntries;    //making an array to store the entries in the file
    int matrix[size];
    int pos = 0;

    int variable = 0;
    while(pos &lt; size){
        inFile &gt;&gt; variable;
        matrix[pos] = variable;
        ++pos;
    }
    cout&lt;&lt; numEntries &lt;&lt; "entries have been read"&lt;&lt; endl; 
    inFile.close();
    for(int i = 0; i &lt; pos; ++i)
        cout &lt;&lt; matrix[i] &lt;&lt; endl; //printing out the entries
    return 0;
}
</code></pre>

<p>When I execute the .cpp file I keep getting the error message:</p>

<pre>terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)</pre>

<p>I have gathered this has to do with a memory shortage or variables falling out of the main() function, but I can not figure out how to address the problem in this specific situation. If it is relevant, I am working on a Linux computer.</p>