Dan Rosenstark
Dan Rosenstark

Reputation: 69787

Using Byte* Instead of NSData: Is my code okay?

This code all works, but I'm basically blundering around my lack of knowledge in C. The code works and does seem to be faster than creating NData instances every time I need to make a method call. But is it okay (no leaks, no pointer gotchas)?

I'm particularly worried about the cast to Byte* which was necessary to get the compiler to pipe down:

Here's is the code, simplified:

- (BOOL) isThisMethodOkay {
    // I have a length, range and an NSData instance
    Byte bytes[self.data.length]; 
    [self.data getBytes:&bytes range:range];
    return [self doSomething:bytes length:length]
}

- (BOOL) whatAboutThis {
    return [self doSomething:(Byte*)self.data.bytes length:self.data.length];
}

- (BOOL) doSomething:(Byte*)bytes length:(NSUInteger)length {
    return (length == CHECK_LENGTH && data1(bytes) == CHECK_DATA_1);
}

static int data1(Byte* bytes) {
    int retVal = (int)bytes[1];
    return retVal;
}

Note: all code is under ARC.

Upvotes: 0

Views: 472

Answers (2)

Joe
Joe

Reputation: 57179

There are no memory leaks since bytes is a VLA which uses the stack. If you plan on handling any large amounts of data you may want to consider allocating that data on the heap and then freeing it when done. (You also should be able to use uint8_t instead of Byte)

- (BOOL) isThisMethodOkay {
    // I have a length, range and an NSData instance
    uint8_t *bytes = malloc(self.data.length); 
    [self.data getBytes:&bytes range:range];

    BOOL result = [self doSomething:bytes length:length];
    free(bytes);
    return result;
}

Upvotes: 1

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

This code is fine as you are not using malloc wchich allocates the memory in heap. There is no leak you are just creating a local Byte array.

Upvotes: 1

Related Questions