Casting pointers & Rule 5-2-7

Moderators: david ward, misra cpp

Post Reply
Posts: 1
Joined: Thu Feb 23, 2012 5:01 pm
Company: INDRA

Casting pointers & Rule 5-2-7

Post by rfrutos » Tue Feb 28, 2012 1:38 pm

The 5-2-7 rule says:
An object with pointer type sall not be converted to an unrelated pointer type, either directly or indirectly
and then shows some examples of casting between classes and structs, my question is if that is extensible to castings to primary types.
What I would like to do is something like:

Code: Select all

typedef struct SC_MsgFrameToRbc
  uint32_t idIxl;
  uint32_t size;
  uint8_t frame[MAX_SIZE_FRAME];
} SC_MsgFrameToRbc;

SC_MsgFrameToRbc *msgReceived = NULL;
SC_MsgFrameToRbc msgSended = NULL;
char *buffer = NULL;

msgSended.idIxl = 1;
msgSended.size = 2

// Simulates sending message
memcpy(buffer, reinterpret_cast<char *>(&msgSended), sizeof(SC_MsgFrameToRbc)); // Compliant ??

// Message reception
msgReceived = reinterpret_cast<SC_MsgFrameToRbc *>(buffer); // Compliant ??
where the memcpy simulates other system-dependent code that implements message sending, would the two castings be compliant?

Posts: 1
Joined: Thu Dec 17, 2015 5:12 am
Company: Lockheed Martin Australia

Re: Casting pointers & Rule 5-2-7

Post by tvan » Thu Jan 21, 2016 5:22 am

I've similar rule 5-2-7 non-compliant. Does anyone know how to get around this?

struct sockaddr_in address = sockaddr_from(bind_port);
const int32_t output = bind(sock_fd, reinterpret_cast<struct sockaddr*>(&address), sizeof(address));

misra cpp
Posts: 151
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

Re: Casting pointers & Rule 5-2-7

Post by misra cpp » Tue Oct 11, 2016 10:36 am

The interpretation is correct, the casting to char* is not permitted (though can be allowed as a deviation). However, this rule may be changed in a TC to match that of MISRA C:2012, that allows casting to char* as an exception
Posted by and on behalf of
the MISRA C++ Working Group

Post Reply

Return to “6.4 Standard conversions (C++)”