Solved

C memcpy() in Objective-C method

Posted on 2010-11-30
2
2,570 Views
Last Modified: 2013-11-25
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
Comment
Question by:Type25
2 Comments
 
LVL 24

Accepted Solution

by:
fridom earned 500 total points
ID: 34246565
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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now