Strlen Acting Weird and I don't know how to solve it!

Hi everyone, I'm currently developing a mesh network to send sensor data.

I'm stumble on a problem which is very confusing to me.

What I'm trying to do is send the bytes of float by accessing it through union.

typedef  union{
  double lat;
  uint8_t ch[8];
}union_send; 

int main(){
    lat_compress.lat = 10.823929100;
    SEGGER_RTT_printf(0,"length of packets %d\n",sizeof(lat_compress.ch));
    SEGGER_RTT_printf(0,"length of packets %d\n",sizeof(lat_compress.lat));
    SEGGER_RTT_printf(0,"length of packets 2 %d\n",strlen(lat_compress.ch));

}

But when I'm try different compiler, it's appeared different from my board.

typedef union{
    double lat;
     uint8_t ch[8];
}lat_send;
int main() {
    // Write C code here
    
    lat_send lat_s;
    lat_s.lat=10.823929100213;
    printf("str len: %d\n",strlen(lat_s.ch));
    printf("size of: %d\n",sizeof(lat_s.ch));
}

Regards, 

Hoang

Parents
  • The union strategy is ok.

    But you cannot use strlen with binary data. What strlen does is that it counts the number of characters (bytes) not equal to 0x00 until it hits a byte containing 0x00 where it in that case stops.

    Your 8 bytes all contain non-zero bytes so it will continue out of bounds counting characters. For the second compiler the third byte outside your union was the first one to contain 0x00.

    So please, only use strlen for strings where you know you have a valid null terminator at the end within bounds of the character array.

Reply
  • The union strategy is ok.

    But you cannot use strlen with binary data. What strlen does is that it counts the number of characters (bytes) not equal to 0x00 until it hits a byte containing 0x00 where it in that case stops.

    Your 8 bytes all contain non-zero bytes so it will continue out of bounds counting characters. For the second compiler the third byte outside your union was the first one to contain 0x00.

    So please, only use strlen for strings where you know you have a valid null terminator at the end within bounds of the character array.

Children
No Data
Related