如果启用代码优化,生成的代码将根本不会调用malloc
。
.LC0:
.string "%d"
main:
sub rsp, 24
mov edi, OFFSET FLAT:.LC0
xor eax, eax
lea rsi, [rsp+12]
mov DWORD PTR [rsp+12], 0
call __isoc99_scanf
mov eax, DWORD PTR [rsp+12]
cmp eax, 1
je .L4
cmp eax, 2
je .L6
xor eax, eax
add rsp, 24
ret
.L4:
mov eax, 1073741824
.L3:
sub rax, 1
jne .L3
jmp .L4
.L6:
jmp .L6
为了防止它使指针易失:
int main(void){
int x=0;
scanf("%d",&x);
if(x==1){
int * volatile a=malloc(1073741824*sizeof(int));
while(1){
for(size_t i=0;i<1073741824;i++){
a[i]=1;
}
}
}
else if(x==2){
int * volatile b=malloc(1073741824*sizeof(int));
while(1);
}
return 0;
}
现在它应该在这两种情况下都 malloc :
.LC0:
.string "%d"
main:
sub rsp, 24
mov edi, OFFSET FLAT:.LC0
xor eax, eax
lea rsi, [rsp+4]
mov DWORD PTR [rsp+4], 0
call __isoc99_scanf
mov eax, DWORD PTR [rsp+4]
cmp eax, 1
je .L10
cmp eax, 2
je .L11
xor eax, eax
add rsp, 24
ret
.L10:
mov edi, 1
sal rdi, 32
call malloc
mov QWORD PTR [rsp+8], rax
.L4:
mov eax, 1073741824
.L3:
mov rdx, QWORD PTR [rsp+8]
sub rax, 1
jne .L3
jmp .L4
.L11:
mov edi, 1
sal rdi, 32
call malloc
mov QWORD PTR [rsp+8], rax
.L6:
jmp .L6