When you dynamically allocate memory...

...how do you ensure that the memory was available and properly allocated? This is something that really confuses me.

Here's an example of some code that I presume needs error checking to be implemented.

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
  main()
{
        void  append (Node **, Node *);
        void printReport (Node *);

        Student * sPtr;
        Node * newPtr;
        Node * head = NULL;

        string yes_no;
        do
        {
                sPtr = new Student;
                newPtr = new Node(sPtr);

                sPtr->receiveInput();
                append (&head, newPtr);

                cout << "Would you like to enter another student? (y/n)\n";
                cin >> yes_no;
        }while(yes_no == "y" || yes_no == "Y" || yes_no == "Yes" || yes_no == "yes" || "yes_no" == "YES");


        printReport(head);
}
If the memory was not available, an exception of type std::bad_alloc would be thrown, and your handler would begin executing instead of the code that attempts to use the bad pointer. Or, if you don't have such handler, the program would be immediately terminated.
Hmm

So would this kind of coding prevent that?

1
2
3
4
5
6
sPtr = new Student;
if(!sPtr)
{
           cerr << "Error" << endl;
           exit(EXIT_FAILURE);
}


So, essentially, every time I see the keyword "new" (dynamically allocating memory), I write that code to error check?
No, that check is useless: if allocation succeeds, sPtr is not null and the condition in the if is never true. If allocation fails, the exception is thrown and the if() is never executed.
What exactly would you like to prevent? How do you plan to handle the out of memory condition other than by terminating the program?
Topic archived. No new replies allowed.