Reputation: 2106
When alloca can't allocate memory on heap it creates structured exception stackoverflow and program halt with Stackoverflow. Ok. But when _malloca can not allocate memory on heap it says nothing. I allocate great amount of memory and after that use it, but get access violation exception. Example
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
void foo(size_t n) {
int *arr = (int*) _malloca(n*sizeof(int));
size_t i;
for (i = 0; i < n; i++) {
arr[i] = rand();
}
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
_freea(arr);
}
void main() {
foo(900000000000);
_getch();
}
BUT when I use only part of allocated memory, I get no exceptions at all. Example
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
void foo(size_t n) {
int *arr = (int*) _malloca(n*sizeof(int));
size_t i;
for (i = 0; i < 100; i++) {
arr[i] = rand();
}
for (i = 0; i < 100; i++) {
printf("%d ", arr[i]);
}
printf("\n");
_freea(arr);
}
void main() {
foo(900000000000);
_getch();
}
VSE2013 WinDesktop. Oki, you may say, try to catch exception
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
#include <windows.h>
void foo(size_t n) {
int *arr = NULL;
size_t i;
__try {
arr = (int*)_malloca(n*sizeof(int));
} __except (GetExceptionCode() == STATUS_STACK_OVERFLOW) {
int errcode;
printf("_malloca failed!\n");
_getch();
errcode = _resetstkoflw();
if (errcode) {
printf("Could not reset the stack!");
_getch();
_exit(1);
}
}
for (i = 0; i < 100; i++) {
arr[i] = rand();
}
for (i = 0; i < 100; i++) {
printf("%d ", arr[i]);
}
printf("\n");
_freea(arr);
}
void main() {
foo(900000000000);
_getch();
}
but it continue to work. And if use all element of array then again get access violation.
Question: it is bug or a feature?
Upvotes: 0
Views: 493
Reputation: 2106
Yey! I was right that _malloca returns NULL when can not allocate memory using malloc on heap. The problem is in call, that is stupid(((
foo(900000000000);
is invalid, because it is bigger than size_t size on my computer. malloc.h use this function to check size is normal
__inline int _MallocaIsSizeInRange(size_t size)
{
return size + _ALLOCA_S_MARKER_SIZE > size;
}
when I call
foo(INT_MAX);
it returns NULL, as memory can not be allocated.
Upvotes: 2