Objective c 尝试将NSString打印为UTF8String时出现分段错误
在我的hello world示例中,我有以下objective-c代码片段:Objective c 尝试将NSString打印为UTF8String时出现分段错误,objective-c,gnustep,Objective C,Gnustep,在我的hello world示例中,我有以下objective-c代码片段: //hello.m #import <Foundation/Foundation.h> #import "hello.h" void sayHello() { #ifdef FRENCH NSString *helloWorld = @"Bonjour Monde!\n"; #else NSString *helloWorld = @"Hello World\n";
//hello.m
#import <Foundation/Foundation.h>
#import "hello.h"
void sayHello()
{
#ifdef FRENCH
NSString *helloWorld = @"Bonjour Monde!\n";
#else
NSString *helloWorld = @"Hello World\n";
#endif
printf("%s", [helloWorld UTF8String]);
}
//main.m
#import <Foundation/Foundation.h>
#import "hello.h"
int main (int argc, const char * argv[])
{
sayHello();
return 0;
}
//hello.m
#进口
#导入“hello.h”
void sayHello()
{
#ifdef法语
NSString*helloWorld=@“世界你好!\n”;
#否则
NSString*helloWorld=@“Hello World\n”;
#恩迪夫
printf(“%s”,[helloWorld UTF8String]);
}
//main.m
#进口
#导入“hello.h”
int main(int argc,const char*argv[]
{
你好;
返回0;
}
在osx上构建这些东西工作正常,运行正常。但是在ubuntu上编译/链接时(使用GNUStep),在执行二进制文件时会导致分段错误。我在printf语句中明确了铸造操作,但我不知道我做错了什么,也不知道如何解决这个问题
有趣的注意:当使用gcc工具链构建可执行文件时,这很好。我只是在ubuntu上用clang构建它时看到了这个问题
非常感谢您的帮助。为了解决此问题,我将代码更改为:
...
void sayHello()
{
#ifdef FRENCH
NSString *helloWorld = @"${HELLO_WORLD_FRENCH}\\n";
#else
NSString *helloWorld = @"${HELLO_WORLD}\\n";
#endif
NSFileHandle *stdout = [NSFileHandle fileHandleWithStandardOutput];
NSData *strData = [helloWorld dataUsingEncoding: NSASCIIStringEncoding];
[stdout writeData: strData];
}
...
我所说的强制转换是指这样一条特殊的语句:“[helloWorld UTF8String]”
[helloWorld UTF8String]
是一个方法调用,而不是强制转换。请为上下文提供其余代码。您发布的内容不会编译(没有函数/方法等),UTF8String返回NSString的const char*
版本。它的存在与NSString对象的生命周期有关,如果存储管理环境甚至有点损坏,它就很容易被破坏。上面的代码片段就是我试图执行的所有代码。因此,在设置NSString之后,我直接调用printf语句。因此,从我谦虚的角度来看,没有什么事情会搞砸……您是否已经阅读了GNUstep的本教程。好奇的是,你是用openapp启动它的吗?对我来说,你的hello.m文件似乎没有代码问题。