MWE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char u8;
typedef unsigned int u32;
#define GB (1024ul * 1024ul * 1024ul)
#define TEST_SIZE (10)
int zerofy = 1;
static u8 * alloc(u32 size)
{
u8 * res = calloc(size, 1);
if (!res)
{
printf(" * Cannot alloc %u bytes\n", size);
return NULL;
}
else
{
printf(" * Allocated %u bytes [%p]\n", size, res);
}
if (zerofy)
memset(res, 0, size);
return res;
}
static void rapemem(u32 zero)
{
u32 i;
u8 * p[TEST_SIZE];
printf("Switching zerofy to %u\n", zero);
zerofy = zero;
for (i = 0; i < TEST_SIZE; i++)
p[i] = alloc(GB);
for (i = 0; i < TEST_SIZE; i++)
free(p[i]);
}
int main(void)
{
system("free -mh");
printf("\n\n");
rapemem(0);
rapemem(1);
rapemem(0);
return 0;
}
Выхлоп:
alex@alex-thinkpad-l560:~/Разработка/C/Tests/calloc$ gcc -std=c89 poc.c
alex@alex-thinkpad-l560:~/Разработка/C/Tests/calloc$ ./a.out
total used free shared buff/cache available
Память: 7,6G 2,1G 4,2G 396M 1,2G 4,8G
Подкачка: 0B 0B 0B
Switching zerofy to 0
* Allocated 1073741824 bytes [0x7fe248a9b010]
* Allocated 1073741824 bytes [0x7fe208a9a010]
* Allocated 1073741824 bytes [0x7fe1c8a99010]
* Allocated 1073741824 bytes [0x7fe188a98010]
* Allocated 1073741824 bytes [0x7fe148a97010]
* Allocated 1073741824 bytes [0x7fe108a96010]
* Allocated 1073741824 bytes [0x7fe0c8a95010]
* Allocated 1073741824 bytes [0x7fe088a94010]
* Allocated 1073741824 bytes [0x7fe048a93010]
* Allocated 1073741824 bytes [0x7fe008a92010]
Switching zerofy to 1
* Allocated 1073741824 bytes [0x7fe248a9b010]
* Allocated 1073741824 bytes [0x7fe208a9a010]
* Allocated 1073741824 bytes [0x7fe1c8a99010]
* Allocated 1073741824 bytes [0x7fe188a98010]
* Cannot alloc 1073741824 bytes
* Cannot alloc 1073741824 bytes
* Cannot alloc 1073741824 bytes
* Cannot alloc 1073741824 bytes
* Cannot alloc 1073741824 bytes
* Cannot alloc 1073741824 bytes
Switching zerofy to 0
* Allocated 1073741824 bytes [0x7fe248a9b010]
* Allocated 1073741824 bytes [0x7fe208a9a010]
* Allocated 1073741824 bytes [0x7fe1c8a99010]
* Allocated 1073741824 bytes [0x7fe188a98010]
* Allocated 1073741824 bytes [0x7fe143fff010]
* Allocated 1073741824 bytes [0x7fe103ffe010]
* Allocated 1073741824 bytes [0x7fe0c3ffd010]
* Allocated 1073741824 bytes [0x7fe083ffc010]
* Allocated 1073741824 bytes [0x7fe043ffb010]
* Allocated 1073741824 bytes [0x7fe003ffa010]
WTF вообще? Теперь и calloc выделению доверять нельзя? Да здравствуют SIGSEGV без вариантов проверить выделение?
Я знаю про оптимистичное выделение, но всю жизнь эта ботва была только с malloc, calloc от этой херни был свободен так как занулял память.