Reputation: 1
#include<iostream>
#include <intrin.h>
using namespace std;
unsigned __int64 TimeValue=0;
unsigned __int64 rdtsc(void)
{
return __rdtsc();
};
void time_start() { TimeValue=rdtsc(); }
long long time_stop() {
return (rdtsc()-TimeValue);
}
int main()
{
long x[262144],i,k,r;
int j;
x[0] = 0;
for (i=1; i<262144; i++)
{
long r = rand()%i;
x[i] = x[r];
x[r] = i;
}
time_start();
for (j=0; j<1000; j++)
for (k=0, i=0; i<262144; i++)
k = x[k];
cout<<time_stop()/1000/262144;
}
In the program I need to create an array size of 1 megabyte. When debugging a program on the line long x [262144]
, an error occurs: An unhandled exception "0x00ff1997" in the "dgdxgdrfy.exe": 0xC00000FD: Stack overflow. Why is this and how to fix it?
Upvotes: 0
Views: 3024
Reputation: 33252
You can use static long x[262144]
; It does move the allocation outside the stack and you don't modify your code at all.
Upvotes: 1
Reputation: 308130
Local variables get allocated on the stack, but the stack is limited. You can probably increase the limit with a switch on the compiler.
The problem is the very large array you've declared. One simple fix will change it from being on the stack to being dynamically allocated:
std::vector<long> x(262144);
Upvotes: 3
Reputation: 39698
Basically, you should dynamically allocate the x array, as is seen in this article. The below example was pulled out from the text, if you change it to be appropriate for your case, it should work fine.
double *num;
num = (double *) malloc (BUFSZ* sizeof(double))
Upvotes: 0
Reputation: 70929
This happens because a local array is allocated on the stack. You can avoid this by using a dynamic array(one created with new), a vector or by declaring the array in the global scope.
Upvotes: 2
Reputation: 47373
Try to declare it as a global variable - outside the main
method(). Otherwise it will be allocated on the stack which is far smaller than the heap. Another solution is to use dynamic allocation with new
, but this is more error prone.
Upvotes: 3