By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,841 Members | 840 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,841 IT Pros & Developers. It's quick & easy.

without using STL in linux, how to allocate large memory by "new" in C++?

P: 5
I know STL vector works. But in case STL is not available,
what can one do to allocate large memory size in c++ through
operator "new"? For instance, I am writing a sort algorithm, and
here's part of the code:

const int range = 1000000;

int *array = new int(range);
if (array == 0) cout<<"null ptr returned"<<endl;

for (int i=0; i<range; i++)
*(array+i) = rand()%(10*range);

If 'range' is around 10000, the above code works.
But if it is large, then segmentation fault occurs after i=33790.
It happens every time after i reaches 33790. Or, if the array is double,
then seg fault will happen right after i=33790/2 = 16895.

What is wrong in the code?

it seems to me that the heap size available to my program is not
big enough. I used ulimit -a to check and it shows 10240 for stack size.
One more doubt is ulimit -s gives 10240 (man ulimit says in bytes)
but ulimit -a says kbytes. Which one is right?

I've also tried using array:
int array[1000000];
the code works for this particular size, but with the size increasing to
about 3M, seg fault happened too.

In general, how to deal with the need of using large chunk of memory in
c++ without using STL?
Jan 19 '08 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 9,197
There's something about your Linux that has limited the size of the CRT heap.

I have done what you are trying to do many times and it works fine. I don't think it's your code.

BTW: If new fails, it does not return a 0. Instead it throws a bad_alloc exception.
Jan 20 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.