ios - iOS插件中的malloc错误

标签 ios objective-c c unity3d

我遇到 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/

相关文章:

ios - 减小按钮文字大小

objective-c - 全局套接字启动(AsyncSocket)

C、乘法、位运算或*

写入后计算文件偏移量

ios - 通过iBeacon监控和测距与CoreBluetooth scanForPeripheralsWithServices检测信标

cocoa-touch - 是否有像 TableView 表单渲染器 View Controller 这样的 cocoa touch 属性页?

objective-c - 如何向我的项目添加头文件夹?

c - fscanf 没有将字符串读入数组

iOS CPU 事件突然停止

macos - Core Graphics 笔划宽度在直线和圆弧之间不一致?