-3
#include <iostream>
#include <string>
using namespace std; 
class books {
private:
books *arr;
public:
books() {
    arr = new books[10];
}
};

int main() {
books a;
cout << "helloo";
return 0;
}

Will someone please tell me what is wrong with this code? The program just runs and crashes.

1 Answers1

3

Will someone please tell me what is wrong with this code? The program just runs and crashes.

Consider how the program is executed line by line:

You create an object of class book. Since it was default initialized, the default constructor will be called. The default constructor allocates 10 instances of book. Since those instances were default initialized, their default constructor is called. During the execution of the constructor of the first object, an array of 10 book instances is allocated. Since those instances were default initialized, their default constructor is called. During the execution of the constructor of the first object, an array of 10 book instances is allocated. Since those instances were default initialized, their default constructor is called. During the execution of the constructor of the first object, an array of 10 book instances is allocated. Since those instances were default initialized, their default constructor is called. During the execution of the constructor of the first object, an array of 10 book instances is allocated. ...

Can you see the problem? You have an ininitely recursive function that will not stop until it has taken all of stack space, at which point the program crashes. Such crash is called a "Stack Overflow".


Another wrong with the code that's not related to the crash: You never delete the memory that you allocated. It is a bad idea to use a bare pointer to dynamically allocated memory.

To create a tree structure with multiple children, I suggest following:

class books {
    std::vector<books> arr;
    // no constructor
};

This way, you won't leak memory, and you get to have leaf instances with no children, so there is no infinite recursion.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • "_until it has taken all of stack space_" Since only one of the `books` is allocated with automatic storage duration (most commonly on stack), and the rest are created with dynamic storage duration (with `new` operator) - it will, most likely, be running until it has consumed all available memory, and crash due to thrown `bad_alloc`. – Algirdas Preidžius Oct 25 '17 at 09:03
  • @AlgirdasPreidžius the constructor calls (and prehaps the allocator calls) each get their own stack frame, which uses stack memory. Sure, it is also possible to crash to `bad_alloc` if the computer has very little memory and offers a relatively big stack, or if OS overcommits, then OOM killer would kill it for being naughty. But I find stack overflow the most likely case. – eerorika Oct 25 '17 at 09:07