我有函數將整數轉換爲字節數組(iPhone版)。爲了增加動態性,我使用malloc分配數組。但我認爲這會泄漏記憶。什麼是管理這個內存最好的方式,釋放使用malloc分配內存的最佳方法
+ (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;
}
致電時,
int x = 500;
unsigned char * bytes = [Util intToByteArray:x];
我想避免由於呼叫免費(字節),調用函數不知道或者不明確的人都知道,內存是分配和不釋放。
釋放它最後由'free()'? –
這種方法的問題在於,函數的調用者不知道是否釋放指針而不查看實現或註釋。這就是OP爲什麼要求替代品的原因。 – nhahtdh
使用NSData來包裝字節 –