我的gcc(版本4.6.1)已将其优化掉。
$ cat 7680489.c
#include <stdlib.h>
#define SIZE 100
int main(void) {
double *a;
size_t i;
// 使用calloc函数初始化元素
a = calloc(SIZE, sizeof *a);
for (i = 0; i < SIZE; i++) a[i] = a[i];
free(a); // 释放内存空间
return 0;
}
$ gcc -std=c89 -O3 -S 7680489.c
$ cat 7680489.s
.file "7680489.c"
.section .text.startup,"ax",@progbits
.p2align 4,,15
.globl main
.type main, @function
main:
.LFB3:
.cfi_startproc
subq $8, %rsp
.cfi_def_cfa_offset 16
movl $8, %esi
movl $100, %edi
call calloc
movq %rax, %rdi
call free
xorl %eax, %eax
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
.LFE3:
.size main, .-main
.ident "GCC: (Debian 4.6.1-4) 4.6.1"
.section .note.GNU-stack,"",@progbits
这段代码没有循环。当使用malloc
而不是calloc
时,汇编输出非常相似。我切换到calloc
,以避免对象具有不确定的值(感谢R..)。
-O3
选项编译时,汇编中不会生成那个循环,只有malloc
调用被保留了。提供此信息仅供参考。 - Mat