以下代码编译正常:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
extern int errno ;
int main ( void )
{
FILE *fp;
int errnum;
fp = fopen ("testFile.txt", "rb");
if ( fp == NULL )
{
errnum = errno;
fprintf( stderr, "Value of errno: %d\n", errno );
perror( "Error printed by perror" );
fprintf( stderr, "Error opening file: %s\n", strerror( errnum ) );
exit( 1 );
}
fclose ( fp );
}
Run Code Online (Sandbox Code Playgroud)
但我不能编译它:
gcc-8 -Wall -Wextra -Werror -Wstrict-prototypes
Run Code Online (Sandbox Code Playgroud)
我得到以下内容:
program.c:6:1: error: …Run Code Online (Sandbox Code Playgroud) 以下程序使用 gcc 8.2.1 生成此内容:
警告:类型限定符在转换结果类型 [-Wignored-qualifiers] 上被忽略 int * const ptrCast = const_cast(ptr);
int main() {
int i = 0;
const int * const ptr = &i;
int * const ptrCast = const_cast<int * const>(ptr);
return *ptrCast;
}
Run Code Online (Sandbox Code Playgroud)
编译为:gcc -Wignored-qualifiers test.cc
根据我对 const_cast 的理解,这不应该发出警告。任何人都可以验证这一点吗?
今天我尝试从这里解决一个测验,当我到达问题3时,有以下代码:
#include <stdlib.h>
int main(void){
int *pInt;
int **ppInt1;
int **ppInt2;
pInt = (int*)malloc(sizeof(int));
ppInt1 = (int**)malloc(10*sizeof(int*));
ppInt2 = (int**)malloc(10*sizeof(int*));
free( pInt );
free( ppInt1 );
free( *ppInt2 );
}
Run Code Online (Sandbox Code Playgroud)
问题是:
在C程序上面选择正确的语句:
A - malloc() for ppInt1 and ppInt2 isn’t correct. It’ll give compile time error.
B - free(*ppInt2) is not correct. It’ll give compile time error.
C - free(*ppInt2) is not correct. It’ll give run time error.
D - No issue with any of the malloc() and …Run Code Online (Sandbox Code Playgroud) 我想在gcc8.2下启用数组边界检查,因此它可以帮助检查在编译期间数组下标是否超出范围,它可能会给出如下警告:
array subscript is above array bounds [-Warray-bounds]
我使用coliru进行了演示:
#include <iostream>
struct A
{
int a;
char ch[1];
};
int main()
{
volatile A test;
test.a = 1;
test.ch[0] = 'a';
test.ch[1] = 'b';
test.ch[2] = 'c';
test.ch[3] = 'd';
test.ch[4] = '\0';
std::cout << sizeof(test) << std::endl
<< test.ch[1] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
编译并运行以下命令:
g++ -std=c++11 -O2 -Wall main.cpp && ./a.out
Run Code Online (Sandbox Code Playgroud)
输出显示如下,没有任何警告或错误。
8
b
Run Code Online (Sandbox Code Playgroud)
那么gcc8.2是否支持数组边界检查?如何启用它?
编辑:
更进一步,基于第一个答案,如果删除volatilein line volatile A test;,是否可以启用数组边界检查?
谢谢。