Search code examples
ccastingtype-conversionmicrocontroller

Char to uint8 incorrect on microcontroller explanation?


I am working on a project on a SAME70 Microcontroller. I had the need to convert from char to uint8_t. I was verifying that it was doing this correctly.

I noticed that when I ran this code to print out the final product:

char test[] = "hey this is a message from the MCU which I can make as large as I want it to be";

int main ( void )
{
    /* Initialize all modules */
    SYS_Initialize ( NULL );
    USART1_Write((uint8_t*)test, sizeof((uint8_t*)test));
}

The data printed out is incorrect. Only the first word "hey" gets printed. However, if I do this instead:

char test[] = "hey this is a message from the MCU which I can make as large as I want it to be";
uint8_t test2[79];
int sizedata = 0;

int main ( void )
{
    /* Initialize all modules */
    SYS_Initialize ( NULL );
    sizedata = sizeof(test);
    memcpy(test2,test,sizedata);
    USART1_Write(test2, sizeof(test2));

the conversion works correctly and everything gets printed. In both cases I gave it the same type as an input so it seems to me that the conversion isn't happening correctly. Does anyone know what I'm doing wrong here?


Solution

  • sizeof((uint8_t*)test) is wrong. This is the size of a pointer uint8_t*. You should pass the size of the array sizeof(test) instead.

    Also

    uint8_t test2[79];
    
    sizedata = sizeof(test);
    memcpy(test2,test,sizedata);
    

    is wrong. The string in the array test is 79-character long, so the array has 80 elements including the terminating null-character and therefore sizeof(test) is 80. On the other hand, the destination test2 has only 79 bytes. Therefore this memcpy performs dangerous out-of-range access.

    You should use

    uint8_t test2[sizeof(test)];
    

    instead. Or if you perfer to use magic numbers (I don't recommend this), you should write

    sizedata = 79;
    

    instead of

    sizedata = sizeof(test);