Hi,
I am goint to create a very large array but have this error when running this code

#include <iostream>
#include <limits.h>
#include <cstddef>
#include <cmath>
using namespace std;

int main()
{
    cout << UINT_MAX << " " << ULLONG_MAX << endl;
    cout << pow(pow(24,2),4) << endl;

    unsigned long long int n = pow(pow(24,2),4) ;
    cout << n << endl;

    double * p = new double (pow(pow(24,2),4));
    for (unsigned long long int i = 0; i < n; i++)
        p[i] = i;
    delete [] p;

    return 0;
}

The running stops at i = 16895 giving

Debugger name and version: GNU gdb 6.8-debian
Program received signal SIGSEGV, Segmentation fault.

What's the ways to deal with large size array? I am not sure it C++ std library's various containers will work but I guess they might be too slow and not efficient, so it is slightly better to stick to normal array?

Thanks in advance!

Recommended Answers

All 2 Replies

Too big!! It's not reasonable to allocate that much memory, think of another way.

You've forgotten the [ ] around the array size in the initializer of p. Thus you are declaring p to point to a single double of value n. As you attempt to read memory past this first value you eventually get a segfault.

However, if you fix that problem, another will arise. You are asking to allocate 110,075,314,176 elements, each 8 bytes long, for a total of 880,602,513,408 or about 820GB. So unless you've got a terabyte of RAM you shouldn't run this program.

For that reason, a huge array is usually implemented as a "sparse array" (look that up).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.