0

I was trying a basic program to copy elements form one array to another. The source array is having more elements. While copying elements from source to destination i only copy few elements from source array.

My source array contains some hex value.

As i am printing the destination array in hex form the last element is different. i.e that elements unknowingly adds up ffffff

Here is the sample program

void String_Copy(char *src, char *dest, int length)
{
    for (int i=0; i<length; i++)
    {
        dest[i] = src[i];
    }
}

int main(void)
{
    char firstStr[] = {0x01,0x03,0x02,0x13,0x88,0xB5,0x12};
    char secStr[5];

    String_Copy(firstStr,secStr,5);

    for (int i=0;i<5;i++)
    {
        printf("%02x ",secStr[i]);
    }

}

Here i want to copy only five elements and print the output.

Expected Output: 01 03 02 13 88

Getting Output: 01 03 02 13 ffffff88

Where are these ffffff are coming from???

enter image description here

What is happening behind the scene?????

Thanks in advance

Devjeet Mandal
  • 345
  • 1
  • 4
  • 23

1 Answers1

1

What you see is the result of sign-extending. Your platform obviously has a signed char type, so you already have implementation defined behavior in your initialization:

char firstStr[] = {0x01,0x03,0x02,0x13,0x88,0xB5,0x12};

0x88 can't be represented in your char type, probably, the maximum value would be 0x7f. The result of a conversion to a signed type is implementation-defined if the type can't represent the value. In your case, it results in some negative number.

Now, your argument to printf() is subject to integer promotion rules, it's converted to an int. For a negative number, this means adding 1 bits in the extra places, that's why you see a bunch of 0xf hex digits when trying to print this as an unsigned. This is btw not well-defined either, %x expects an unsigned, but you give it a signed value.

The simplest solution would be to just use unsigned char everywhere. Also, change the format string to %02hhx to tell printf() it's just an unsigned char, not an unsigned int.