有没有“-O0”优化级别可以打开GCC标志“-Waggressive-loop-optimizations”?

时间:2018-02-12 22:04:04

标签: c gcc c11 gcc7

就像标题提示我想知道是否有办法打开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编译器通知我:

INPUT:

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

有谁知道为什么会发生这种情况,如果有可能的方法将此标志设置为ON?: -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的时候。

0 个答案:

没有答案