Ios NSData转换时堆缓冲区溢出

Ios NSData转换时堆缓冲区溢出,ios,objective-c,cocoa,cocoa-touch,Ios,Objective C,Cocoa,Cocoa Touch,我注意到了XCode 8中AddressSanitizer的有趣行为。在一种情况下,它会导致捕获断点:AddressSanitizer:地址上的堆缓冲区溢出,但我真的不明白为什么: char * buffer = malloc(length); memset(buffer, 0, length); [output getBytes:buffer length:length]; stringOutput = [NSString strin

我注意到了XCode 8中AddressSanitizer的有趣行为。在一种情况下,它会导致捕获断点:AddressSanitizer:地址上的堆缓冲区溢出,但我真的不明白为什么:

    char * buffer = malloc(length);
    memset(buffer, 0, length);
    [output getBytes:buffer
              length:length];
    stringOutput = [NSString stringWithUTF8String:buffer]; // here is crash
同:

stringOutput = [NSString stringWithUTF8String:output.bytes];
但所有的情况都很好:

stringOutput = [[NSString alloc] initWithData:output
                                         encoding:NSUTF8StringEncoding];
另外,经过一些实验,我发现如果我们在缓冲区的末尾添加“0”,一切都会好起来:

char * buffer = malloc(length + 1);
memset(buffer, 0, length + 1);
[output getBytes:buffer
          length:length];
stringOutput = [NSString stringWithUTF8String:buffer];

这种行为对我来说是不可预料的,因为我已经在实时代码中使用了十几次stringWithUTF8String:output.bytes,没有任何问题。。。那么我错在哪里呢?

[nsstringwithutf8string:
常量char*
作为参数, 并从给定的内存位置开始读取字节,直到终止
0
字节 找到了如果分配和写入到的内存中没有
0
字节 内存,它将继续读取未定义的内存,
甚至从 无效的内存位置。该方法没有关于的信息 定义了从给定指针开始的字节数

另一方面,
[[NSString alloc]initWithData:encoding:][/code>
获取一个
NSData
参数(包括指向数据的指针和长度),并从
该对象。

[nsstringwithutf8string:buffer]
读取字节,直到找到NUL终止符。如果分配和填充的内存中没有零字节,将读取未定义的内存。但是为什么stringOutput=[NSString stringWithUTF8String:output.bytes];导致撞车?我假设Cocoa足够聪明,可以解决这种情况下的问题?因为该方法现在无法知道许多字节已定义或有效。您正在告诉Cocoa有尾随零字节的字节。你在撒谎。科科非常信任别人。你撒谎,你会得到你应得的。酷,谢谢你,马丁。只是没想到那地方会有问题。。。