有一个main.c
文件,其内容为:
#include "memory.h"
#include "stdint.h"
#define MOLECULE_API_DECORATOR
MOLECULE_API_DECORATOR const uint8_t MolDefault_ByteOpt[0] = {};
int main(int argc, char *argv[]) {
uint32_t size = sizeof(MolDefault_ByteOpt);
const uint8_t *expected = MolDefault_ByteOpt;
const uint8_t *actual = NULL;
if (memcmp(actual, expected, size) != 0){
return 1;
}
return 0;
}
然后我用gcc 12.2.1通过gcc -Werror -Wall main.c
编译main. c,将得到:
main.c: In function ‘main’:
main.c:8:5: error: offset ‘0’ outside bounds of constant string [-Werror=array-bounds]
8 | int main(int argc, char *argv[]) {
| ^~~~
main.c:6:38: note: ‘MolDefault_ByteOpt’ declared here
6 | MOLECULE_API_DECORATOR const uint8_t MolDefault_ByteOpt[0] = {};
| ^~~~~~~~~~~~~~~~~~
main.c:10:31: error: offset ‘0’ outside bounds of constant string [-Werror=array-bounds]
10 | const uint8_t *expected = MolDefault_ByteOpt;
| ^~~~~~~~~~~~~~~~~~
main.c:6:38: note: ‘MolDefault_ByteOpt’ declared here
6 | MOLECULE_API_DECORATOR const uint8_t MolDefault_ByteOpt[0] = {};
| ^~~~~~~~~~~~~~~~~~
main.c:8:5: error: offset ‘0’ outside bounds of constant string [-Werror=array-bounds]
8 | int main(int argc, char *argv[]) {
| ^~~~
main.c:6:38: note: ‘MolDefault_ByteOpt’ declared here
6 | MOLECULE_API_DECORATOR const uint8_t MolDefault_ByteOpt[0] = {};
| ^~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
如何更改代码以避免此错误?
我希望比较actual
和expected
,并且编译此代码时不会出现任何警告或错误。
1条答案
按热度按时间xiozqbni1#
C 2018 6.2.5 20说(粗体添加):
而C 2018 www.example.com 1说,如果数组声明符的
[
和]
内部的表达式:6.7.6.2 1 says, if the expression inside[
and]
of an array declarator:由于声明符
MolDefault_ByteOpt[0]
不符合这些规则,因此C标准没有定义该行为。C 2018 7.1.4 1规定:
由于在计算
memcmp(actual, expected, size)
时actual
是空指针,因此参数具有无效值,并且C标准未定义该行为。如何更改代码以避免此错误?
将数组大小设为正数,并传递一个指向
memcmp
的有效指针(可以传递任何const
或未限定对象的地址)。