What is the maximum allowed size of an "unsigned char" array in Visual C++ 6.0?

2.9k views Asked by At

For working with graphics, I need to have an array of unsigned char. It must be 3 dimensional, with the first dimension being size 4, (1st byte Blue, 2nd byte Green, 3rd byte Red, 4th byte Unused). A simple array for a 640x480 image is then done like this:

unsigned char Pixels[4][640][480]

But the problem is, it always crashes the program immediately when it is run. It compiles fine. It links fine. It has no errors or warnings. But when it's run it immediately crashes. I had many other lines of code, but it is this one I found that causes the immediate crash. It's not like I don't have enough RAM to hold this data. It's only a tiny amount of data, just enough for a single 640x480 full color image. But I've only seen such immediate crashes before, when a program tries to read or write to unallocated memory (for example using CopyMemory API function, where the source or destination either partially or entirely outside the memory space of already defined variables). But this isn't such a memory reading or writing operation. It is a memory allocating operation. That should NEVER fail, unless there's not enough RAM in the PC. And my PC certainly has enough RAM (no modern computer would NOT have enough RAM for this). Can somebody tell me why it is messing up? Is this a well known problem with VC++ 6.0?

2

There are 2 answers

0
TonyK On

If this is inside a function, then it will be allocated on the stack at runtime. It is more than a megabyte, so it might well be too big for the stack. You have two obvious options:

(i) make it static:

static unsigned char Pixels[4][640][480];

(ii) make it dynamic, i.e. allocate it from the heap (and don't forget to delete it when you have finished):

unsigned char (*Pixels)[640][480] = new unsigned char[4][640][480];
...
delete[] Pixels;

Option (i) is OK if the array will be needed for the lifetime of the application. Otherwise option (ii) is better.

2
sjdowling On

Visual C++ by default gives programs 1MB of stack. The size the array you are trying to allocate on the stack is 1200KB which is going to bust your stack. You need to allocate your array on the heap. std::vector is your best bet for this.

using namespace std;
vector<vector<vector<unsigned char>>> A(4, vector<vector<unsigned char>>(640, vector<unsigned char>(480, 0)));

This looks a bit more confusing but will do what you want in terms of initialising the array and means you don't have to worry about memory leaks.

Alternatively if this isn't an option then it is possible to increase the stack size by passing /STACK: followed by the desired stack size in bytes to the linker.

Edit: in the interests of speed you may wish to use a single allocated block of memory instead:

std::unique_ptr<unsigned char [][640][480]> A(new unsigned char [4][640][480]);