DEV Community


Posted on

[DopeTales] HackScripts Memory Allocation Testing

Very often we want to test maximum memory that can be allocated at user space. It has interesting use cases. Mine relates to 4gb memory shadow creation. Basically I implemented sample DDR of size 4gb and took snapshot of simulated memory at intervals. so i need to know before hand if i have that much memory available before running actual application. Following script allows me to do that in simple loops.

#include <stdio.h>
#include <stdlib.h>

#define MINREQ      0xFFF   // arbitrary minimum
int main(void)
    unsigned int required = (unsigned int)-1; // adapt to native uint
    void *mem = NULL; 
    while (mem == NULL) {
        printf ("Required %X\n", required);
        mem = malloc (required);
        if ((required >>= 1) < MINREQ) {
            if (mem) free (mem);
            printf ("Cannot allocate enough memory\n");
            return (1);

    free (mem);
    void * array[4096];
    unsigned int count  =0;
    for( ;count < 4096; count++) {
    mem = malloc (required);
    if (mem == NULL) {
        printf ("Cannot enough allocate memory  %d \n",count);
       array[count] = mem;

    printf ("Memory size allocated = %X\n", required );
    for(int  i = 0  ; i <count ; i++)
    free (array[i]);
    return 0;
Enter fullscreen mode Exit fullscreen mode

It tries to allocate minimum size then goes on continuously till largest possible at current moment.

Happy Hacking!

Top comments (0)