Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2731
  • Last Modified:

C memcpy() in Objective-C method

Hi, I'm writing a method in objective-c who's aim it is, is to prefix some data with a 4-byte length of the following data.  However, my C is incredibly rusty and after running allocations with and without the following method, I'm led to believe it leaks (I'm not surprised).

Could anyone help me out.
 
-(NSData *) addPrefixMessageFramingToData:(NSData *) msgData
{
	NSInteger length = [msgData length]; 
	unsigned char *lengthPrefix = (unsigned char*)&length;
	
	unsigned char lengthPrefixBuffer[4] = { 0, 0, 0, 0 };
	memcpy(lengthPrefixBuffer, (unsigned char *)lengthPrefix, 4);
	
	NSMutableData *newSend = [[NSMutableData alloc] initWithBytes:lengthPrefixBuffer length:4];
	[newSend appendData:msgData];
	
	return [newSend autorelease];
}

Open in new window

0
Type25
Asked:
Type25
1 Solution
 
fridomCommented:
I'm afraid this mix between Objects and "primitive" data types won't work.
I do not dare to speculate what this does:
NSInteger length = [msgData length];
      unsigned char *lengthPrefix = (unsigned char*)&length;

Why don't you take the lenght at the 4 bytes to it and fill the Mutable Data then?

0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now