[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Max size of data in C++ prog?



On Sat, Dec 18, 2004 at 07:10:22PM -0500, Marc Shapiro wrote:
> Is there a maximum size to the data segment in a C++ program?  More 
> specifically, I am trying to write a program with a very large array. 
> The program compiles OK (since C/C++ do no bounds checking on arrays), 
> but segfaults when I try to run it.  The limit seems to be at just under 
> 8MB.  Is there a way to allocate more space for data?

there are two different data segments for a C or C++ program,
the stack and the heap.

stack space is (apparently) limited under Linux.
If you declare an array like this in a function:

  char c[10*1024*1024];

and write to it all, this will cause a segfault on Linux.

The heap can get much bigger, you can malloc as much as you want on the heap
(up to the limits of VM and process address space) and it won't segfault, e.g.

  char *c = malloc(100*1024*1024);
  int i;
  for (i=0; i<size; ++i)
  	c[i] = 'x';
  free(c);

you need to:

#include <malloc.h>

to use malloc.


C++ allocates data on the heap when you use "new", and the STL containers
allocate their elements on the heap.  For example these are ok:

  char *c = new char[100*1024*1024];
  // ...
  delete[] c;

  vector<int> v;
  int i;
  for (i=0; i<10000000; ++i)
  	v.push_back(i);


As Gregory pointed out (and I had forgotten to mention) global and static
variables go on the heap too.



Reply to: