Reputation: 2359
I am running gcc 4.8.4 and compiling with options:
CXXFLAGS+= -Wall -std=c++11 -pedantic -lpthread
I want to zero a structure using 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));
This results in warning:
In function ‘void* memset(void*, int, size_t)’, inlined from ‘void sendMsgPduError(TMsgPduError*, uint32)’ at ../MessageHandling.cpp:174:46:
/usr/include/x86_64-linux-gnu/bits/string3.h:84:70: warning: call to void* __builtin___memset_chk(void*, int, long unsigned int, long unsigned int) will always overflow destination buffer [enabled by default]
return __builtin___memset_chk (__dest, __ch, __len, __bos0 (__dest));
I realise that this is a sensible warning but I don't know how to modify the code to fix it.
I read that std::fill_n is preferred to memset. Is that correct?
If so, how would I replace memset by fill_n?
Upvotes: 0
Views: 4577
Reputation: 180235
-std=c++11
is a rather unusual flag for what's really C89 code. But I digress.
The proper fix is just
TErrorInd p_msg { 0 };
No char[]
(improper alignment), no memset
(not needed as it's already zeroed)
Upvotes: 2
Reputation: 8871
Check the value of sizeof(TErrorInd), for some reason gcc thinks that it is greater than sizeof(uint8) * 16. Maybe you did not counted alignment bytes, computing the struct size.
Upvotes: 2