Home > OS >  how to get rid of casting warning
how to get rid of casting warning

Time:10-08

#define NUMOFDMABUF 20
u8 *data[NUMOFDMABUF];

int main()
{
    for (u32 i = 0; i < NUMOFDMABUF; i  )
    {
        data[i] = (void *)(RX_BUFFER_BASE   (i * MAX_PKT_LEN)); //-Wint-to-pointer-cast
    }
}

This is for bare metal application and i want to explicitly set memory addresses of ram locations to an array of pointers. The code works, but how do i write the code to avoid the occurrence of this warning?

If i explicitly set the address as a value, no issues... but when i do it this way it throws the the warning. I am brain farting, so thoughts appreciated :)

CodePudding user response:

The text of the warning produced by gcc is more descriptive.

warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

The OP mentions in the comments how RX_BUFFER_BASE is defined:

#define RX_BUFFER_BASE 0x40000000

That macro is later textually expanded in the line

data[i] = (void *)(RX_BUFFER_BASE   (i * MAX_PKT_LEN));

The type of i is a non standard U32, I'll assume it to be a 32-bit unsigned integer. MAX_PKT_LEN is undisclosed, but I'll assume it to be defined as RX_BUFFER_BASE.

Now, the type of an integer constant is the first type in which the value can fit1, so 0x40000000 could be an unsigned int or an unsigned long int depending on the implementation, or if we consider fixed width types, an uint32_t, but not an uint64_t.

Using an integer suffix, like 0x40000000ull, would have forced it to be an unsigned long long.

We can assume2 that the other variables in that expression have the same type, while pointers, in OP's implementation, have a wider representation. Therefore the warning.

The asker could have used a type specifically designed for this kind of pointer arithmetic, like uintptr_t, which is an unsigned integer type capable of holding a pointer to void:

#include <stdint.h>
const uintptr_t buffer_base = 0x40000000;

1) C17 standard (ISO/IEC 9899:2018): 6.4.4.1 Integer constants (p: 45-46) or see e.g. https://en.cppreference.com/w/c/language/integer_constant#The_type_of_the_integer_constant

2) Sorry, that's a lot assumptions, I know, but it's not entirely my fault.

CodePudding user response:

how do i write the code to avoid the occurrence of this warning?

This may-or-may-not work in all environments.
It is just a proposal that may work for this OP.

I haven't done "bare metal" stuff to any serious degree.
But this compiles on my old computer without warnings...

int main() {
    uint8_t *d[20];
    memset( d, 0, sizeof d ); // start clean

    for( uint32_t i = 0; i < sizeof d/sizeof d[0]; i   )
        d[i]  =  0x2468   ( i * 256 ); // NB " ="

    return 0;
}

I'm not going to go anywhere near dereferencing any of those pointers though.

  • Related