Unless you have a VLA or alloca() , here is an extremely complex, but portable, stack technique:
int foo(int size) { if (size <= 64*1024) { unsigned char arr[64*1024]; return bar(arr, size); } else if (size <= 1*1024*1024) { unsigned char arr[1*1024*1024]; return bar(arr, size); } else if (size <= 64*1024*1024) { unsigned char arr[64*1024*1024]; return bar(arr, size); } else return -1;
I do not particularly recommend this technique, but it will give you different sized memory blocks allocated on the stack instead of the heap.
David R Tribble
source share