Meerkat
Meerkat

Reputation: 281

No change in heap?

I wrote a simple function in order to check if malloc works. I create 1 Gb array, fill it with numbers, but the heap does not seem to change. Here is the code:

#include <stdio.h>
#include <assert.h>  // For assert()
#include <stdlib.h>  // For malloc(), free() and realloc()
#include <unistd.h>  // For sleep()

static void create_array_in_heap()
{
    double* b;
    b = (double*)malloc(sizeof(double) * 1024 * 1024 * 1024);
    assert(b != NULL);    // Check that the allocation succeeded

    int i;
    for (i=0; i<1024*1024*1024; i++);
        b[i] = 1;

    sleep(10);

    free(b);
}

int main()
{
    create_array_in_heap();

    return 0;
}

screenshot of Linux' system monitor screenshot of Linux' system monitor

Any ideas why ?

Upvotes: 2

Views: 55

Answers (1)

Pascal Cuoq
Pascal Cuoq

Reputation: 80325

EDIT: a simpler explanation is given in the comments. But my answer applies once the ; has been removed.

An agressive optimizing compiler, such as Clang (Compiler Explorer link), can see that the only important part of your function create_array_in_heap is the call to sleep. The rest has no functional value, since you only fill a memory block to eventually discard it, and is removed by the compiler. This is the entirety of your program compiled by Clang 7.0.0 with -O2:

main:                                   # @main
        pushq   %rax
        movl    $10, %edi
        callq   sleep
        xorl    %eax, %eax
        popq    %rcx
        retq

In order to benchmark any aspect of a program, the program should have been designed to output a result (computing and discarding the result is too easy for the compiler to optimize into nothing). The result should also be computed from inputs that aren't known at compile-time, otherwise the computation always produces the same result and can be optimized by constant propagation.

Upvotes: 3

Related Questions