【问题标题】:How to avoid __builtin___memset_chk warning?如何避免 __builtin___memset_chk 警告?
【发布时间】:2016-12-25 05:40:06
【问题描述】:

我正在运行 gcc 4.8.4 并使用选项进行编译:

CXXFLAGS+= -Wall -std=c++11 -pedantic -lpthread

我想使用 memset 将结构归零:

typedef struct
{
    TSfMsgHeader    errorHeader;
    TErrorHeader    errorType;
    TErrorDetails   errorDetails;
}TErrorInd;

uint8 g_errorIndBlock[16];

TErrorInd* p_msg = (TErrorInd *)&g_errorIndBlock[0];
memset((int*)p_msg, 0, sizeof(TErrorInd));

这会导致警告:

在函数'void* memset(void*, int, size_t)'中, 从 ../MessageHandling.cpp:174:46:

处的“void sendMsgPduError(TMsgPduError*, uint32)”内联

/usr/include/x86_64-linux-gnu/bits/string3.h:84:70: 警告:调用 void* __builtin___memset_chk(void*, int, long unsigned int, long unsigned int) 将始终溢出目标缓冲区[默认启用]

return __builtin___memset_chk(__dest, __ch, __len, __bos0 (__dest));

我意识到这是一个明智的警告,但我不知道如何修改代码来修复它。

我读到 std::fill_n 比 memset 更受欢迎。对吗?

如果是这样,我将如何将 memset 替换为 fill_n?

【问题讨论】:

  • 另外,为什么要投到int*
  • g_errorIndBlock[16]; 为什么是 16?你怎么知道的?

标签: c++ gcc


【解决方案1】:

检查 sizeof(TErrorInd) 的值,由于某种原因 gcc 认为它大于 sizeof(uint8) * 16。可能你没有计算对齐字节,计算结构体大小。

【讨论】:

    【解决方案2】:

    -std=c++11 对于真正的 C89 代码来说是一个相当不寻常的标志。但我离题了。

    正确的解决方法只是

    TErrorInd p_msg { 0 };
    

    没有char[](不正确对齐),没有memset(不需要,因为它已经归零了)

    【讨论】:

    • 在原始帖子中没有TErrorInd 数据。 p_msgTErrorInd*
    猜你喜欢
    • 2021-02-04
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2014-03-21
    • 2014-10-23
    • 1970-01-01
    • 2019-10-04
    相关资源
    最近更新 更多