允许编译器优化重新分配吗? [英] Are compilers allowed to optimize out realloc?

查看:72
本文介绍了允许编译器优化重新分配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样一种情况,对不必要的realloc调用进行优化会很有用.但是,似乎Clang和GCC都没有这样做( Compiler Explorer (godbolt.org)) -尽管我看到通过多次调用malloc进行了优化.

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.

示例:

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);
}

为什么Clang和GCC都没有对其进行优化? -他们不允许这样做吗?

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.

如果剩余150个可分配内存的字节,
data = malloc(100); data = realloc(data, 200);返回NULL,其中消耗了100个字节(并泄漏了)并保留了50个字节.

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);返回NULL,其中消耗了0个字节(没有泄漏)并且保留了150个字节.

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.

成功的malloc(n); ... realloc(p, 2*n)malloc(2*n);不同,因为...可能已经设置了一些内存.

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.

这篇关于允许编译器优化重新分配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆