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.
A few things:
The
chartype (andsigned charandunsigned 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
intobject, if this is the case, it is not necessary to allocate more space for it, simply take the address of theintand cast it to a pointer tounsigned char *. If the byte order is wrong you can use theNSSwapIntfunction to swap the order of the bytes in theintand then take the address and cast tounsigned char *. For example:This cast is legal and reading from
bytesis 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 tofreewhen 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
bytesinto aNSDatainstance:Make sure your method follows the usual object ownership rules.