Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error: terminate called after throwing an instance of 'std::bad_alloc'

Tags:

c++

I wrote the code pasted below to perform the following tasks in the order in which they are stated:

  1. Read an input file and count the number of entries in it
  2. Create an array of appropriate size (size equal to number of entries)
  3. Go back to the beginning of the input file and read it again
  4. Store the entries in an array
  5. Print out the number of entries in the file and the entries themselves.

Here is my code:

#include <iostream>
#include <fstream>
#include <exception>

using namespace std;

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

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

    if(!inFile){
        cout << "file not found" << 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 < size){
        inFile >> variable;
        matrix[pos] = variable;
        ++pos;
    }
    cout<< numEntries << "entries have been read"<< endl; 
    inFile.close();
    for(int i = 0; i < pos; ++i)
        cout << matrix[i] << endl; //printing out the entries
    return 0;
}

When I execute the .cpp file I keep getting the error message:

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

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.

like image 263
2good4this Avatar asked Oct 08 '16 18:10

2good4this


1 Answers

This code has 3 holes:


First hole: int numEntries. Later you do: ++numEntries;

You increment unspecified value. Not sure if it's UB, but still bad.


Second and third hole:

const int length = numEntries;
int* arr = new int[length];

And

const int size = numEntries;
int matrix[size];

numEntries has unspecified value (first hole). You use it to initialize length and size - that is Undefined Behaviour. But let's assume it is just some big number - you allocate memory of unspecified size (possibly just very big size), hence the std::bad_alloc exception - it means you want to allocate more memory that you have available.

Also, matrix is VLA of unspecified size, which is both non-standard and Undefined behaviour.

like image 176
xinaiz Avatar answered Sep 20 '22 09:09

xinaiz