Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

c - Are compilers allowed to optimize out realloc?

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 (Compiler Explorer (godbolt.org)) - 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?

question from:https://stackoverflow.com/questions/53373421/are-compilers-allowed-to-optimize-out-realloc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ensure ..., even if empty code, did not set any memory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...