Are compilers allowed to optimize-out realloc?

  • A+
Category:Languages

I came across a situation where it would be useful to have unnecessary calls to realloc being optimized out. However, it seems like neither clang nor gcc do such a thing (godbolt). - Although I see optimizations being made with multiple calls to malloc.

The example:

void *myfunc() {     void *data;     data = malloc(100);     data = realloc(data, 200);     return data; } 

I expected it to be optimized to something like the following:

void *myfunc() {     return malloc(200); } 

Why is neither clang nor gcc optimizing it out? - Are they not allowed to do so?

 


Are they not allowed to do so?

Maybe, but optimization not done in this case may be due to corner functional differences.


If 150 bytes of allocatable memory remain,
data = malloc(100); data = realloc(data, 200); returns NULL with 100 bytes consumed (and leaked) and 50 remain.

data = malloc(200); returns NULL with 0 bytes consumed (none leaked) and 150 remain.

Different functionality in this narrow case may prevent optimization.


Are compilers allowed to optimize-out realloc?

Perhaps - I would expect it is allowed. Yet it may not be worth the effect to enhance the compiler to determine when it can.

Successful malloc(n); ... realloc(p, 2*n) differs from malloc(2*n); when ... may have set some of the memory.

It might be beyond that compiler's design to insure ..., even if empty code, did not set any memory.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: