Bad memory allocation?

When I run my program I get an error message: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc

How do I resolve this?

I'm trying to create a dynamically allocated array of structures and return it to the pointer created in main. I noticed that this error only occurs when trying to cout the members in main, as I am now where it crashes. If I try to cout (display) the members in the other function, it shows up perfectly.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

struct Movie
{
    int year;
    string name;
    string director;
    int timesCalled;
};

Movie *readMovieInfo(int &size);

int main()
{
    int size;
    Movie *movieList;

    movieList = readMovieInfo(size);

    for (int i = 0; i < size; i++)
    {
        cout << movieList[i].year << "   ";
        cout << movieList[i].name << "   ";
        cout << movieList[i].director << endl;
    }

    return 0;
}


Movie *readMovieInfo(int &size)
{
    ifstream inFile;
    string file;
    Movie *movieList;
    movieList = new Movie[size];

    cout << "What is the name of the file you'd like to open? ";
    getline(cin, file);
    file.append(".txt");
    inFile.open(file.c_str());
    if(!inFile)
    {
        cout << "Can't open the input file!" << endl;
        exit(111);
    }

    inFile >> size;

    for (int i = 0; i < size; i++)
    {
        inFile >> movieList[i].year;

        getline(inFile, movieList[i].name, '\"');
		getline(inFile, movieList[i].name, '\"');
		movieList[i].name = movieList[i].name;

		getline(inFile, movieList[i].director, '\"');
		getline(inFile, movieList[i].director, '\"');
		movieList[i].director = movieList[i].director;
    }
    cout << "test";
    inFile.close();

/*
    for (int i = 0; i < size; i++)
    {
        cout << movieList[i].year << "   ";
        cout << movieList[i].name << "   ";
        cout << movieList[i].director << endl;
    }
*/
    return movieList;
}
Last edited on
The problem is that you have not assigned any value to size before you use it on line 42.
Oh my... Haha.. Thank you for pointing out such a bad mistake.
Topic archived. No new replies allowed.