Size of array too large

Hello! I am writing a small program and I need an array that contains 1.000.000.000 numbers. When I compile it, I get the error "size of array 'v' is too large." What is the maximum limit of elements an array can store?

OS: Windows 8.1 32 bit
IDE:CodeBlocks
"v" is an int
Compiler is GNU gcc
Thanks in advance!
First of all, it depends on environment. 32-bit OS allows less memory for an application than a 64-bit OS.

Second, you don't say what kind of array you are using, so I presume a plain statically allocated local array.
Local variables are in stack memory, which is quite limited.

Dynamic allocation uses free memory area. Try to use std::vector


Look at "size_type" in http://www.cplusplus.com/reference/array/array/
Then look at http://www.cplusplus.com/reference/limits/numeric_limits/
With those you can test some limits on your environment.
Try this 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <Windows.h>

std::string GetLastWinError();

void main(void)
{
  int *array = NULL;
  size_t size = 1000000000;

  array = (int *) VirtualAlloc(array, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

  if (array == NULL)
  {
    std::cout << GetLastWinError();
  }
  else
  {
    std::cout << "Memory allocation successful\n\n";
    VirtualFree(array, 0, MEM_RELEASE);
  }
  system("pause");
}

std::string GetLastWinError ()
{
  LPVOID lpMsgBuf;
  LPVOID lpDisplayBuf;
  DWORD dw = GetLastError ();

  FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_FROM_SYSTEM, NULL, dw,
                 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf,
                 0, NULL);

  std::ostringstream oss;
  oss << "Windows Error ";
  oss << dw << " :" << (LPCSTR)lpMsgBuf;

  LocalFree (lpMsgBuf);

  return oss.str();

}
You are allocating 1 billion numbers. If those numbers are integers, then they are probably 4 bytes long. You're running a 32 bit operating system which means that a process is limited to 4GB total (probably less: the OS usually reserves part of the address space for various other things).

Bottom line: you can't allocate a 4GB array when have only 4GB for the entire process.

What are you doing with the array? Chances are excellent that with a little thought, you'll find that you don't actually need to store all of the numbers simultaneously.
Topic archived. No new replies allowed.