就像标题一样,我想知道是否有办法打开 GCC 标志
-Waggressive-loop-optimizations
当优化级别是-O0
或根本不使用-OX
时。
让我们看看下面的例子:
#include <stdio.h>
int main ( void ){
int arr[4] = { 0 };
for ( int i = 0 ; i < 5 ; i++ ){
arr[i] = i+1;
}
for ( int j = 0; j < 4 ; j++ ){
printf("Arr[%d] = %d\n", j, arr[j] );
}
}
如您所见,在i == 4
这里:
for ( int i = 0 ; i < 5 ; i++ )
程序在其边界之外读取数组。
使用以下 GCC 标志编译-O1
器-O3
通知我这一点:
输入:
gcc-7 -Wpedantic -std=c11 -Wall -Wextra -Werror -O1
输出:
program.c: In function ‘main’:
program.c:6:16: error: iteration 4 invokes undefined behavior [-Werror=aggressive-loop-optimizations]
arr[i] = i+1;
~~~~~~~^~~~~
program.c:5:5: note: within this loop
for ( int i = 0 ; i < 5 ; i++ ){
^~~
cc1: all warnings being treated as errors
但当然它不与-O0
.
我正在尝试以下操作:
gcc-7 -Wpedantic -std=c11 -Wall -Wextra -Werror -Waggressive-loop-optimizations -O0 program.c -o program
甚至以下(没有-O0
:
gcc-7 -Wpedantic -std=c11 -Wall -Wextra -Werror -Waggressive-loop-optimizations program.c -o program
编译器只是忽略这个标志:
-Waggressive-loop-optimizations
有谁知道为什么会发生这种情况以及是否有可能打开此标志的方法?:
-Waggressive-loop-optimizations
编辑:
我需要这个,因为例如当我编译上面的程序时:
gcc-7 -Wpedantic -std=c11 -Wall -Wextra -Werror -Wstrict-prototypes -Wmissing-prototypes -Wmisleading-indentation -Wduplicated-cond -Wold-style-definition -Wconversion -Wshadow -Winit-self -Wfloat-equal -Wwrite-strings -Wpointer-compare -Waggressive-loop-optimizations -g program.c -o program
然后我做:
valgrind --leak-check=full --track-origins=yes ./program
valgrind 没有报告什么,因为我认为编译器优化了它(我认为):
michi@michael ~/Compile $ valgrind --leak-check=full --track-origins=yes ./program
==5818== Memcheck, a memory error detector
==5818== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==5818== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==5818== Command: ./program
==5818==
Arr[0] = 1
Arr[1] = 2
Arr[2] = 3
Arr[3] = 4
==5818==
==5818== HEAP SUMMARY:
==5818== in use at exit: 0 bytes in 0 blocks
==5818== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==5818==
==5818== All heap blocks were freed -- no leaks are possible
==5818==
==5818== For counts of detected and suppressed errors, rerun with: -v
==5818== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
无论如何,在评论中,对编辑部分和问题本身存在一些误解。
不,我不需要在valgrind
这里进行修复,编辑只是为了解释没有捕获超出其边界的访问数组的情况之一,因为该标志-Waggressive-loop-optimizations
不像使用优化级别时那样工作-O1
,-O2
或者-O3
。