Dynamic memory

Hi guys , I have just read the article about dynamic memory in the documentation and tried to compile the code provided with it . But when I enter a large number that the required memory can't be allocated it gives me Debug Error , in spite of using nothrow Method
Here is the code
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
// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;

int main ()
{
  int i,n;
  int * p;
  cout << "How many numbers would you like to type? ";
  cin >> i;
  p= new (nothrow) int[i];
  if (p == 0)
    cout << "Error: memory could not be allocated";
  else
  {
    for (n=0; n<i; n++)
    {
      cout << "Enter number: ";
      cin >> p[n];
    }
    cout << "You have entered: ";
    for (n=0; n<i; n++)
      cout << p[n] << ", ";
    delete[] p;
  }
  return 0;
}

I use Windows 7 ultimate 64 bit & Visual studio 2010
Try building/running it as a release instead of a debug...
biaspoint :
It doesn't work !!
Try
1
2
3
4
5
6
7
8
9
int main ()
{
  int i,n;
  // Init the value of p to null 
  int * p(0);  // <---------  Look here
// etc...
 
  return 0;
}


EDIT: Never mind, nothrow should return a null if failed.

EDIT: What is the size of the allocation you are trying to allocated to make it fail? The largest value i (signed int) can hold is 2147483647 bytes just over 2Gbytes.
Like if I enter:
./a.out
Enter: 4000000000
i: 134513706

I don't think you are getting the size of the number that you think. Make i a 64-bit number.
1
2
3
4
// Add 
#include <stdint.h>
// And make i
uint64_t i(0);
Last edited on
Check out edit above.
> Make i a 64-bit number.

What is the need for such non-portable constructs when we have a std::size_t?
Good point, didn't realize it wasn't standard (given the std in the name). Like the fact that the number of bits is right in your face.
1
2
3
#include <cstdint>

std::uint64_t i ;


is standard (C++11).

My point was that the standard does not specify that std::size_t is a 64-bit unsigned integral type.
Oh. Thanks, like that. Just C++11 only?
Last edited on
Also note that std::uint64_t is optional. A conformant C++11 implementation doesn't need to have that type.
Topic archived. No new replies allowed.