我遇到 malloc 错误:
"pointer being free was not allocated"
我正在尝试为 Unity 构建一个简单的测试 iOS 插件。
H 文件只是声明,M 文件是:
const char* _getDayAsString(int day)
{
return [[DotWPlugin getDayAsString:day] UTF8String];
}
@implementation DotWPlugin
+ (NSString*)getDayAsString:(int)day
{
if(day == 0)
return @"Sunday";
else if(day == 1)
return @"Monday";
else if(day == 2)
return @"Tuesday";
else if(day == 3)
return @"Wednesday";
else if(day == 4)
return @"Thursday";
else if(day == 5)
return @"Friday";
else if(day == 6)
return @"Saturday";
else
return @"Invalid";
}
@end
看来问题是我正在尝试将 NSString* 转换为 const char* 但它不喜欢那样。
最佳答案
根据 NSString
reference, UTF8String
method :
The returned C string is a pointer to a structure inside the string object, which may have a lifetime shorter than the string object and will certainly not have a longer lifetime. Therefore, you should copy the C string if it needs to be stored outside of the memory context in which you called this method.
在您的例子中,getDayAsString:
方法返回的 NSString
在 _getDayAsString()
函数退出时被释放。也就是说,UTF8String
方法返回的char*
也被释放了。
在您的 _getDayAsString()
中,请创建一个由 UTF8String
方法返回的以 null 结尾的字符串的副本并返回该副本。
关于ios - iOS插件中的malloc错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24348491/