0

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.

Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421

2 Answers2

1

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.

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
1

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;
}
Joe
  • 56,979
  • 9
  • 128
  • 135
  • Thanks! 1) what would be "large amounts?" I'm probably not going to exceed 32 bytes ever and 2) what about the second method, ´whatAboutThis´? – Dan Rosenstark Feb 07 '12 at 14:59
  • 1
    If you know you will not exceed 32bytes you should be fine. It looks like the main thread on iOS is limited to [1MB stack size](http://stackoverflow.com/questions/2918691/is-there-stack-size-in-iphone). What about this is fine as well as long as `Byte` is some form of char (1 byte) – Joe Feb 07 '12 at 15:03