Solved

C memcpy() in Objective-C method

Posted on 2010-11-30
2
2,575 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

Network it in WD Red

There's an industry-leading WD Red drive for every compatible NAS system to help fulfill your data storage needs. With drives up to 8TB, WD Red offers a wide array of solutions for customers looking to build the biggest, best-performing NAS storage solution.  

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
why debugging a macro i s difficult 10 28
memory leak detection 9 68
negation in C function 14 144
Resolve Dependency Issues 4 42
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…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops 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.

919 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

12 Experts available now in Live!

Get 1:1 Help Now