Skip to content

Instantly share code, notes, and snippets.

@alk
Created June 21, 2014 21:43
Show Gist options
  • Save alk/6d8a907fccc8f18b414d to your computer and use it in GitHub Desktop.
Save alk/6d8a907fccc8f18b414d to your computer and use it in GitHub Desktop.
alk-malloc-test
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <assert.h>
#define HISTORY_SIZE (1024*1024)
#define CHUNK_MIN (2*1024*1024)
#define CHUNK_MAX (32*1024*1024)
__attribute__((weak))
extern void MallocExtension_GetStats(char* buffer, int buffer_length);
static
void print_stats(void)
{
char stats_buf[1024*1024];
if (!MallocExtension_GetStats) {
printf("Cannot print stats!\n");
return;
}
MallocExtension_GetStats(stats_buf, sizeof(stats_buf));
printf("Stats:\n%s", stats_buf);
}
static struct {
int size;
void *ptr;
} history[HISTORY_SIZE];
static volatile int exit_signalled;
static
void sigint_handler(int dummy)
{
exit_signalled = 1;
}
int main()
{
unsigned iterations = 0;
signal(SIGINT, sigint_handler);
assert(RAND_MAX > (CHUNK_MAX - CHUNK_MIN));
assert(RAND_MAX > HISTORY_SIZE);
srand(0);
while (!exit_signalled) {
size_t size = (size_t)(rand()) % (CHUNK_MAX - CHUNK_MIN) + CHUNK_MIN;
unsigned slot = iterations % HISTORY_SIZE;
void *old = history[slot].ptr;
void *newc = 0;
if ((size % 4) == 0) {
slot = (unsigned)(rand()) % HISTORY_SIZE;
}
if ((size % 4) != 0) {
newc = malloc(size);
if (!newc) {
printf("allocation failed!\n");
exit(1);
}
} else {
size = 0;
}
history[slot].ptr = newc;
history[slot].size = size;
free(old);
iterations++;
if ((iterations % 5000000) == 0) {
print_stats();
}
if ((iterations % 50000000) == 0) {
unsigned i;
printf("Freeing everything\n");
for (i = HISTORY_SIZE-1; i >= 0; i--) {
free(history[i].ptr);
history[i].size = 0;
history[i].ptr = 0;
}
print_stats();
printf("This is stats after freeing everything\n");
}
}
print_stats();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment