AngelClient(38032,0x10a155340) malloc: *** error for object 0x600000016d40: Invalid pointer dequeued from free list
*** set a breakpoint in malloc_error_break to debug
給byte數(shù)組不足位補零操作鸟顺,然后報上述錯誤
#pragma mark - 字符串轉(zhuǎn)為長度為length的data,不足位自動補零
+(NSData *)stringToData:(NSString *)string length:(NSUInteger)length{
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8); ;
NSData *data = [string dataUsingEncoding:enc];
Byte *byte = (Byte *)[data bytes];
//錯誤寫法
for (int i = (int)data.length; i < length; i++) {
byte[i] = 0;
}
NSData * data16 = [[NSData alloc] initWithBytesNoCopy:byte length:length deallocator:^(void * _Nonnull bytes, NSUInteger length) {
}];
return data16;
}
正確的寫法是
#pragma mark - 字符串轉(zhuǎn)為長度為length的data导匣,不足位自動補零
+(NSData *)stringToData:(NSString *)string length:(NSUInteger)length{
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8); ;
NSData *data = [string dataUsingEncoding:enc];
Byte *byte = (Byte *)[data bytes];
//先開辟空間屏镊,然后重新給byte賦值
NSData * data16 = [[NSData alloc] initWithBytes:byte length:length];
Byte *byte1 = (Byte *)[data16 bytes];
for (int i = (int)data.length; i < length; i++) {
byte1[i] = 0;
}
return data16;
}