Solved

C memcpy() in Objective-C method

Posted on 2010-11-30
2
2,635 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.

690 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