尝试将NSString打印为UTF8String时出现分段错误 [英] Segmentation fault when attemping to print NSString as UTF8String

查看:106
本文介绍了尝试将NSString打印为UTF8String时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的世界示例中,我有以下Objective-C片段:

I have the following objective-c snippet in my hello world example:

//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;
}

在osx上构建这些东西可以正常工作并按预期运行.但是当在ubuntu上编译/链接它(使用GNUStep)时,执行二进制文件时会导致分段错误.我在printf语句中将其固定在了强制转换操作上,但是我不知道我在这里做错了什么或如何解决这个问题.

building this stuff on osx works fine and runs as expected. But when compiling/linking it on ubuntu (using GNUStep) results in an segmentation fault when executing the binary. I nailed it down to the casting operation in the printf statement, but I have no clue what I'm doing wrong here or how I can solve this.

有趣的注意事项:使用gcc工具链生成可执行文件时,此方法可以很好地工作.我只是在ubuntu上用clang构建它时看到了这个问题.

Interesting note: This works fine when using gcc toolchain to build the executable. I just see this issue when building it with clang on ubuntu.

非常感谢您的帮助.

推荐答案

为解决此问题,我最终将代码更改为以下内容:

To fix this issue, I ended up changing my code to the following:

...
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];
}
...

这篇关于尝试将NSString打印为UTF8String时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆