Thursday, June 2, 2022

[SOLVED] Casting char[] to usigned int gives: dereferencing type-punned pointer will break strict-aliasing rules

Issue

I have a line in some legacy's source code:

#define MAXMSG 1024
...
char m_recvBuf[MAXMSG];
unsigned int msgLength = ntohl(*((unsigned int *)m_recvBuf));

This yields the following warning:

x.cpp: In member function ‘bool xx::cccc(std::string&)’:
x.cpp:308: warning: dereferencing type-punned pointer will break strict-aliasing rules

How can I get rid of this warning ?

my compile line:

g++ -c -g -O2 -Wall -DDEBUG_ON -D_VERSION_=\"1.0.0\" `xml2-config --cflags` -I../src -I./common -I. -I../../test/ -o common/xx.o common/xx.cpp

$ g++ --version
g++ (GCC) 4.4.6 20110731 (Red Hat 4.4.6-3)

Solution

The problem with your code is that violates strict aliasing rules and thus it's potentially unsafe.

You can either hide the warning with -Wno-strict-aliasing (this won't solve your problem), modify your data structure or avoid the problem entirely by specifying position and length of your binary copy as Matt suggested (probably the best option):

unsigned int msgLength; 
memcpy(&msgLength, m_recvBuf, sizeof(msgLength)); 
msgLength = ntohl(msgLength);

Notice: I've not been getting the error with clang 3.4 and gcc 4.8.2 in -O3, that means the compiler might have optimized the warning away. Anyway that doesn't assure you your code is safe.



Answered By - Marco A.
Answer Checked By - Candace Johnson (WPSolving Volunteer)