【发布时间】:2016-05-20 19:01:14
【问题描述】:
我真的不知道哪个应该是正确的标题,但我会尽力解释它,请耐心等待。
今天我发现了这个GCC flag =>> -Wlarger-than=len:
Warn whenever an object of larger than len bytes is defined.
所以我决定试一试。让我们看看下面的程序:
#include <stdio.h>
#include <string.h>
int main(void){
char ptr[12] = "Mississippi";
size_t len1 = sizeof ptr;
printf("Len1 = %zu\n", len1);
char a[len1];
strcpy(a, ptr);
printf("\nA = %s\n", a);
}
作为输出返回:
Len1 = 12
A = Mississippi
所以程序看起来不错,但是如果我用len == 10 将-Wlarger-than=len 标志打开而不是12:
gcc -Wall -Wextra -Werror -Wlarger-than=10 program.c -o program
当我期望 12 时,我得到了 16:
program.c:5:14: error: size of ‘ptr’ is 12 bytes [-Werror=larger-than=]
char ptr[12] = "Mississippi";
^~~
program.c:10:14: error: size of ‘({anonymous})’ is 16 bytes [-Werror=larger-than=]
char a[len1];
^
program.c:10:14: error: size of ‘({anonymous})’ is 16 bytes [-Werror=larger-than=]
program.c:10:14: error: size of ‘({anonymous})’ is 16 bytes [-Werror=larger-than=]
program.c:10:14: error: size of ‘({anonymous})’ is 16 bytes [-Werror=larger-than=]
为什么会这样?我对此感到困惑,因为这一行:
char a[len1];
我认为它会是:
char a[12];
如果我将size_t len1 = sizeof ptr; 更改为size_t len1 = strlen(ptr) + 1;,也会发生同样的事情
【问题讨论】:
-
迟到的评论,但 gcc 有这个标志 -Wvla-larger-than=
会警告您有关 vla 大小的信息。