编译器优化会影响动态内存分配吗?

时间:2019-01-05 21:16:32

标签: c memory-management

我知道有时候编译器会删除未使用的数组。

但是我的问题是对使用malloc分配的动态变量或只是堆栈变量有影响吗?

malloc是编译时操作还是运行时?

如果是运行时,编译器可以删除使用malloc分配的数组,还是只能删除固定大小的数组?

2 个答案:

答案 0 :(得分:4)

由于内存分配不是可观察到的行为,因此允许编译器删除malloc及其系列。

例如,gccclang optimize these functionsreturn 42-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;
}

更复杂的是由c发出的successfully optimizedreturn 42

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

但是您应该期望不高:这种优化是不寻常的,并且通常是不可靠的。

答案 1 :(得分:0)


您已更改问题:

带有外部链接的变量不会被优化。其他可能是。它们不会被“删除”-已被优化-即它们不存在于已编译的代码中

enter image description here

我认为这是不言自明的。