title: C and Objective-C - Correct way to free an unsigned char pointer
body: <p>in my app I create an unsigned char pointer using this function:</p>
  
  <pre><code>- (unsigned char*)getRawData
  {
  // First get the image into your data buffer
  CGImageRef image = [self CGImage];
  NSUInteger width = CGImageGetWidth(image);
  NSUInteger height = CGImageGetHeight(image);
  
  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  
  unsigned char *rawData = malloc(height * width * 4);
  NSUInteger bytesPerPixel = 4;
  NSUInteger bytesPerRow = bytesPerPixel * width;
  NSUInteger bitsPerComponent = 8;
  CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
  CGColorSpaceRelease(colorSpace);
  
  CGContextSetBlendMode(context, kCGBlendModeCopy);
  
  CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), image);
  CGContextRelease(context);
  
  // Now your rawData contains the image data in the RGBA8888 pixel format.
  
  return rawData;
  }
  </code></pre>
  
  <p>And in another class I assign a property to that pointer like so: self.bitmapData = [image getRawData];</p>
  
  <p>Where in this process can I free that malloc'd memory? When I try to free the property in dealloc, it gives me an exc_bad_access error. I feel like I'm missing a fundamental c or objective-c concept here. All help is appreciated.</p>