Why error message doesn't appear when memory could not be allocated?

Hi everyone, I'm new to C++ and at chapter "Dynamic Memory" there is an example with how to use new and delete to allocate memory, but even if there is a message to appear when memory could not be allocated, the error message doesn't appear instead i have this message on my console:

1
2
3
4
5
6
7
8
9
10
How many numbers would you like to type ?
1000000000
terminate called after throwing an instance of 'std::bad_array_new_length'
  what():  std::bad_array_new_length

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Process returned 3 (0x3)   execution time : 15.988 s
Press any key to continue. 


I suppose it is the same thing trying to say it could not allocate memory.
I'm using Code::Blocks as IDE.

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
// C++ Programing

#include <iostream>
#include <new>

using namespace std;

int main()
{
    int i, n;
    int * p;

    cout << "How many numbers would you like to type ?" << '\n';
    cin >> i;

    p = new(nothrow) int[i];

    if(p == nullptr)
    {
        cout << "Error: Memory could not be allocated" << '\n';
    }
    else
    {
        for(n = 0; n < i; n++)
        {
            cout << "Enter number: ";
            cin >> p[n];
        }

        cout << "You have entered these numbers: ";

        for(n = 0; n < i; n++)
        {
            cout << p[n] << ", ";
        }
        cout << '\n';
        delete[] p;
    }

    return 0;
}
Last edited on
I was trying to make the exception works and I tried to push at this number 1.000.000.000
and instead to catch the error message it give me another thing... Am I doing something wrong ??
Don't use int for these large numbers. Use size_t.

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
#include <iostream>

using namespace std;

int main()
{
	size_t i {};

	cout << "How many numbers would you like to type? ";
	cin >> i;

	auto p {new (nothrow) int[i] {}};

	if (p == nullptr)
		cout << "Error: Memory could not be allocated\n";
	else {
		for (size_t n = 0; n < i; ++n) {
			cout << "Enter number: ";
			cin >> p[n];
		}

		cout << "You have entered these numbers:\n";

		for (size_t n = 0; n < i; ++n)
			cout << p[n] << ", ";

		cout << '\n';

		delete[] p;
	}

	return 0;
}



How many numbers would you like to type? 1000000000000
Error: Memory could not be allocated


On Windows.
Ohh, I got it.. soo these examples are old, or just wrong? Because in the web the example is written with int, or maybe just because I use it on windows and on other platform works just fine ?
Probably depends upon whether you're compiing as 32 or 64 bit. Much of web examples assume 32 bit pointers. As well as much of 'old' C++ code. That's why code which 'seemed' to work OK with 32 bit suddenly starts to fail in some cirumstances with 64 bit.

Mine is 7 on 32-bit, and I tried your example , well I just copied and paste TBH. but either way I got the same message not the one I set to appear. :\
Do I have to set my compiler to something? I just set this one:-std=C++11, because some of the examples in the Tutorial was just meaning to use this setting to work properly.
I use MS VS2019 with Windows 7 in release mode. My code above works OK when compiled as both 32 bit and 64 bit.....


How many numbers would you like to type? 10000000000
Error: Memory could not be allocated

How many numbers would you like to type? 1000000000000
Error: Memory could not be allocated


when using 32 bit version. Output above was from 64 bit version.

Last edited on
Well that means.. is something wrong with my system? Or maybe with my compiler? as I use 12.17 code::blocks I know isn't the latest but still I don't get that error, and here my learning c++ stops, cose I understand clearly how it works both ways , but the result is different? Any idea what should I do or just pass over it and go on? :\
When I debug the program when cursor is at this line code:
auto p {new (nothrow) int[i] {}};, I get a message from code::blocks:
Cannot Open File File:../.../.../.../.../src/gcc-5.1.0/libgcc/i386/shmem-win32.c and is not going further.
Last edited on
I search for it on internet and doesn't seems to find anything that can fix it or anyone reporting something similar. Still for now I can only believe it's something wrong with my system , and I do believe that the code above works just fine.
Thank you seeplus for your advice in using
size_t
instead of 'int'. I'll mark it as solved for now since is not a code problem and is something wrong with my sistem or PC. who knows..
> Well that means.. is something wrong with my system? Or maybe with my compiler?

There is nothing very wrong with your compiler or library; an implementation is permitted to impose an upper limit on the maximum new array size that it supports. 1000000000000 may be (looks like it is) too large a value for this implementation.

Try running this:

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
#include <iostream>
#include <new>

int main()
{
	size_t sz = 0 ;

	std::cout << "array size? ";
	std::cin >> sz;

    try
    {
        std::cout << "try to allocate an array of size " << sz << '\n' ;
        int* p = new int[sz] {} ;

        std::cout << "successfully allocated the array: p == " << p << '\n' ;

        // do something with the array

        delete[] p ;
    }

    // std::bad_array_new_length is thrown if such a large array is not supported
    // https://en.cppreference.com/w/cpp/memory/new/bad_array_new_length
    catch( const std::bad_array_new_length&  )
    {
        std::cout << "error: the array size exceeds the maximum value supported by this implementation\n" ;
    }

    // std::bad_alloc is thrown on failure to allocate memory 
    // (when the amount of available free storage is inadequate)
    // https://en.cppreference.com/w/cpp/memory/new/bad_alloc
    catch( const std::bad_alloc& )
    {
        std::cout << "error: failed to allocate the requested amount of memory\n" ;
    }
}
Last edited on
Okay mister.. :) this is working. Still I'm new to C++ as I said before, and some instruction from your code my brain can't process them yet, at least not now, as I didn't arrived at that point, by meaning this I refer to these:

try//catch

These are very new to me , but hey.. as a matter of fact is working and this means like you said 'nothing is wrong with my compiler or library'.

Thank you JLBorges for your answer I'll try to look forward for these instructions in my next lessons :)
Last edited on
That program doesn't use nothrow - just try/catch which is the normal C++ way of dealing with errors.

However, using nothrow as per original, try and see which error is displayed:

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
#include <iostream>

int main() {
	size_t sz {};

	std::cout << "array size? ";
	std::cin >> sz;

	try {
		std::cout << "try to allocate an array of size " << sz << '\n';
		auto p {new (std::nothrow) int[sz] {}};

		if (p == nullptr)
			std::cout << "Error: Memory could not be allocated\n";
		else {
			std::cout << "successfully allocated the array: p == " << p << '\n';

			// do something with the array

			delete[] p;
		}
	}

	catch (const std::bad_array_new_length&) {
		std::cout << "error: the array size exceeds the maximum value supported by this implementation\n";
	}

	catch (const std::bad_alloc&) {
		std::cout << "error: failed to allocate the requested amount of memory\n";
	}

	catch (...) {
		std::cout << "Unhandled exception!\n";
	}
}


try/catch are a part of C++ exception handling.

https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm

C++ exception handling is part of the standard but more than a few programmers hate it. When writing their own code they never use it.

Others swear it is better than sliced bread.

The standard library is stuffed full with exception handling. std::vector::at() vs. operator[], for example. Should a program try to access a vector's element that is out of the vector's range using .at() an exception is thrown. operator[] trying to access a nonexistent element for the vector will result in undefined behavior.
Topic archived. No new replies allowed.