I have function to convert an integer into byte array (for iPhone). To add dynamicity I have allocate the array using malloc. But I think this will leak memory. What's best way to manage this memory,
+ (unsigned char *) intToByteArray:(int)num{
unsigned char * arr = (unsigned char *)
malloc(sizeof(num) * sizeof(unsigned char));
for (int i = sizeof(num) - 1 ; i >= 0; i --) {
arr[i] = num & 0xFF;
num = num >> 8;
}
return arr;
}
When calling,
int x = 500;
unsigned char * bytes = [Util intToByteArray:x];
I want to avoid the call free(bytes) since, the calling function do not know or explicitly knows, the memory is allocated and not freed.
Just call
free(bytes);
when you are done with the bytes (either at the end of method or in dealloc of the class)since you want to avoid the free call, you could wrap your byte[] in a NSData object:
NSData *d = [NSData dataWithBytesNoCopy:bytes length:num freeWhenDone:YES];
A few things:
The
char
type (andsigned char
andunsigned char
) all have a size of 1 by definition, sosizeof(unsigned char)
is unnecessary.It looks like you just want to get the byte representation of an
int
object, if this is the case, it is not necessary to allocate more space for it, simply take the address of theint
and cast it to a pointer tounsigned char *
. If the byte order is wrong you can use theNSSwapInt
function to swap the order of the bytes in theint
and then take the address and cast tounsigned char *
. For example:This cast is legal and reading from
bytes
is legal up untilsizeof(int)
bytes are read. This is accessing the “object representation”.If you insist on using
malloc
, then you simply need to pass the buffer tofree
when you are done, as in:The name of your method does not imply the correct ownership of the returned buffer. If your method returns something that the caller is responsible for freeing, it is conventional to name the method using
new
,copy
, or sometimescreate
. A more suitable name would becopyBytesFromInt:
or something similar. Otherwise you could have the method accept a pre-allocated buffer and call the methodgetBytes:fromInt:
, for example:You could wrap your
bytes
into aNSData
instance:Make sure your method follows the usual object ownership rules.
The conventional way of handling this is for the caller to pass in an allocated byte buffer. That way the caller is responsible for freeing it. Something like:
I would also consider creating an NSData to hold the bytes, this would take care of memory management for you, while still allowing you to alter the byte buffer: