How to return an address of a const struct member in compliance to MISRA from a C function?

  Kiến thức lập trình

I have a C function that gets the address of a struct member and returns it as a void pointer.
The first parameter of the function provides a pointer to the struct. This parameter is provided as const to prevent the struct members being modified by the function.
MISRA 2023 rule C.11.8 however, does not allow to cast a const pointer to a pointer.

Structure type:

typedef struct {
    uint16          ID;
    int16           *In;
    int16           Out;
    int16           V;
    int8            sfr;
} GAIN_FIP16;

C function:

void* Gain_FiP16_GetAddress(const GAIN_FIP16* block, uint16 elementId)
{
    void* addr;
    switch (elementId)
    {
        case 1:
            addr = (void*)block->In;
            break;
        case 2:
            addr = (void*)&block->Out;
            break;
        default:
            addr = NULL;
            break;
    }
    return (addr);
}

The MISRA checker does complain about the cast (void*)&block->Out.
This violates the MISRA rule:

A conversion shall not remove any const, volatile or _Atomic
qualification from the type pointed to by a pointer.

AFAIK I do have the following possibilities:

  • Remove the const qualifier of the first function argument (but that also removes the ‘nice’ read-only behavior)
  • Create a MISRA deviation

Is there possibly another solution to this problem?

Thank you,
Markus

I removed the const qualifier from the block parameter.
This solves the MISRA warning but at the cost of losing the ‘read-only’ feature.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT