Ramtin Mousavi
Ramtin Mousavi

Reputation: 372

Does compiler optimization affect on dynamic memory allocation?

I know sometimes compilers remove unused arrays.

But my question is do the affect on dynamic variables which are allocated using malloc or just the stack variables ?

Is malloc a compile time operation or runtime?

If it is runtime can compiler remove an array which is allocated using malloc or it can only remove the arrays which are fixed size ?

Upvotes: 2

Views: 1051

Answers (2)

0___________
0___________

Reputation: 67546


As you have changed the question:

variables with the external linkage will not be optimized out. Other potentially yes. They are not "removed" - they are optimised out - ie they do not exist in the compiled code

enter image description here

I think it is self explanatory.

Upvotes: 0

user2512323
user2512323

Reputation:

The compiler is allowed to remove malloc and its family because memory allocation is not an observable behavior.

For example, both gcc and clang optimize these functions to just return 42 with -O2:

int foo(){
    malloc(10);
    return 42;
}

int bar(){
    int* p = (int*)malloc(10);
    *p = 17;
    return 42;
}

int qax(){
    int* p = (int*)malloc(10);
    *p = 17;
    int a = *p + 25;
    free(p);
    return a;
}

Even a more complex one is successfully optimized to return 42 by clang:

void bar(int* xs){
    for (int i = 0; i < 10; i++){
        xs[i] = i + 35;
    }
}

int foo(){
    int* xs = (int*)malloc(40);
    bar(xs);
    return xs[7];
}

But you should not expect much: such optimizations are unusual and, in general, unreliable.

Upvotes: 4

Related Questions