0

[EDIT]I wanted write uint64_t to char* array in network byte order to send it as UDP datagram with sendto, uint64_t has 8 bytes so I convert them as follow:

void strcat_number(uint64_t v, char* datagram) {
    uint64_t net_order = htobe64(v);
        for (uint8_t i=0; i<8 ;++i) {
    strcat(datagram, (const char*)((uint8_t*)&net_order)[i]);
    }
}

wchich give me

warning: cast to pointer from integer of different size [-Wint-to-pointer-xast] strcat(datagram, (const char*)((uint8_t*)&net_order)[i]);

how can I get rid of this warning or maybe do this number converting simpler or clearer?

karol wołonciej
  • 109
  • 1
  • 1
  • 10

1 Answers1

1
((uint8_t*)&net_order)

this is a pointer to net_order casted to a uint8_t pointer

((uint8_t*)&net_order)[i]

this is the i-th byte of the underlying representation of net_order.

(const char*)((uint8_t*)&net_order)[i]

this is the same as above, but brutally casted to a const char *. This is an invalid pointer, and it is what the compiler is warning you about; even just creating this pointer is undefined behavior, and using it in any way will almost surely result in a crash.

Notice that, even if you somehow managed to make this kludge work, strcat is still the wrong function, as it deals with NUL-terminated strings, while here you are trying to put binary data inside your buffer, and binary data can naturally contain embedded NULs. strcat will append at the first NUL (and stop at the first NUL in the second parameter) instead of at the "real" end.

If you are building a buffer of binary data you have to use straight memcpy, and most importantly you cannot use string-related functions that rely on the final NUL to know where the string ends, but you have to keep track explicitly of how many bytes you used (i.e. the current position in the datagram).

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299