Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj c adding bytes to uint8_t array between methods?

I'm having an odd problem with obj c adding an extra byte to by uint8_t array.

Here are the two methods that are involved:

ViewController.m

- (void)viewDidLoad {
    // hexData = NSData object
    const uint8_t *hexBytes = [hexData bytes];

    // header is first 3 bytes
    uint8_t headerBytes[] = {hexBytes[0],hexBytes[1],hexBytes[2]};

    // output the size
    NSLog(@"View did load header size: %lu", sizeof(headerBytes));

    // create a MessageHeader object
    MessageHeader *messageHeader = [[MessageHeader alloc] initWithBytes:headerBytes];
}

MessageHeader.h

- (id)initWithBytes:(uint8_t *)bytes {
    self = [super init];
    if(self != nil){
        NSLog(@"Message header init bytes size: %lu", sizeof(bytes));
        NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
        self.bytes = bytes;
    }
    return self;
}

Console output

View did load header size: 3

Message header init bytes size: 4

This is very strange! Outputting the bytes to the screen shows that an extra byte has been appended to the data for no apparent reason. If eef231 is the input then eef23150 is the output in the init method. That extra byte is seemingly random.

I wonder if it could be the cast between uint8_t headerBytes[] and uint8_t *bytes in the init method.

If anyone has any more info on it that would be great. Thanks

like image 573
Thomas Clayson Avatar asked Apr 01 '26 06:04

Thomas Clayson


1 Answers

sizeof is a compile time operator and doesn't do what you think it does.

sizeof on an uint8_t[] gives you the size of that array, which is 1 byte * 3 elements = 3 bytes. It can do this because the array declaration has implicit size information attached.

sizeof on an uint8_t* gives you the size of a pointer, which is 4 bytes on 32 bit systems.

See the wikipedia article on sizeof for a good idea of what it does.

If you want to pass the length of the array, the general convention is to pass an additional length paremeter. Since you are working in objective c, you should pass around an NSData, which can contain an array of data, and also its size.

like image 160
yiding Avatar answered Apr 02 '26 21:04

yiding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!