Reputation: 1
Have problem with sigsegv with huge array. As I find it often is problem with allocating on stack. But I'm allocating this array on heap and still got SIGSEGV. I'm not sure what is wrong.
#include <cstdio>
using namespace std;
#define DATA_SIZE 1000000
static int inputArray[DATA_SIZE];
int* CountOnes(int* data)
{
int outputArray[DATA_SIZE];
int count, i;
for (i = 0; i < DATA_SIZE; i++)
{
count = 0;
while (*(data + i) > 0)
{
if (*(data + i) & 0x01)
count++;
*(data + i) >>= 1;
}
outputArray[i] = count;
}
return outputArray;
}
int main()
{
CountOnes(inputArray);
return 0;
}
I tried allocating with static global array, global array, array allocated with new. Any ideas?
Upvotes: 0
Views: 132
Reputation: 254431
As I find it often is problem with allocating on stack.
Indeed, on most platforms the stack is quite small (typically from a few dozen kilobytes up to a few megabytes), and can easily overflow if you create large automatic objects. Specifically, outputArray
is (probably) four megabytes, which (probably) is too large.
I tried allocating with static global array, global array, array allocated with new.
Any of those should work, but have other issues - static arrays (local or global) prevent reentrancy and thread-safety, and new
requires you to jump through hoops to correctly delete the array. The best option is std::vector<int>
, a dynamic array which manages its (heap-allocated) memory automatically.
Upvotes: 1
Reputation: 74365
Your outputArray
is still allocated on the stack. Use ulimit -s unlimited
to remove the default stack size limit. Also note that you are returning a pointer to a stack array from CountOnes
. That won't work since the array is destroyed on exit from the function and therefore the pointer returned becomes invalid. You should either make outputArray
static or allocate it with the new
operator.
Upvotes: 1