views:

167

answers:

2

Hi, I'm having trouble passing a big array to a function in C.

I declare:

int image[height][width][3]={};

where height and width can be as big as 1500. And when I call:

foo((void *)image,height,width);

which is declared as follows:

int *foo(const int *inputImage, int h, int w);

I get segmentation fault error. What's strange is that if my values are:

height=1200;
width=290;

theres no problem, but when they're:

height=1200;
width=291;

i get the mentioned error. At 4 bytes per integer with both height and width of 1500 (absolute worst case) the array size would be of 27MB which imo isn't that big and shouldn't really matter because I'm only passing a pointer to the first element of the array. Any advice?

+3  A: 

At 27 MB, your array is probably bigger than the stack, which is usually 1 MB. You are corrupting your process as soon as foo starts working with the data. Allocate the array on the heap instead:

typedef int (*image_buf)[height][width][3];
image_buf image = malloc(sizeof(image_buf));
...
Marcelo Cantos
Thanks a lot, that did the trick. I'll read some more, because I still can't see why passing a pointer to the first element overflows the stack.
kirbuchi
@kirbuchi: The stack is used for local variables. You're overflowing the stack not by passing the pointer, but rather by trying to define such a large local array. I imagine it's simply not erroring until you try to access an element that is past your stack space... which occurs in your foo() function.
Matt B.
I did some reading and I think I get it now. Turns out stack space is used for local variables, so when calling foo() it tries to allocate the 27MB on the stack.
kirbuchi
A: 

you can check the default process stack size using 'ulimit -a' on unix systems

   (blocks, -c) 0

data seg size (kbytes, -d) unlimited scheduling priority (-e) 20 file size (blocks, -f) unlimited pending signals (-i) 16382 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) unlimited virtual memory (kbytes, -v) unlimited file locks (-x) unlimited

Pigol