2011-08-31 79 views
0

很简单的问题,EXC_BAD_ACCESS,iphone上的标准c库“打开”?

无论我做什么尝试调用open()的应用程序崩溃,下面都是相关代码的一部分。文件名不是垃圾值,并且包含文件的绝对路径。这在设备和模拟器上失败。

文件名返回的printf:

/用户/ programmingstation7 /库/ Application Support/iPhone 模拟器/ 4.3 /应用/ E2BD16DB-FFBA-45D2-B425-96C981380B85 /文档/ issue2.zip

相关回溯:

#0 0x002132dc in open() 

#1 0x000ddcec in -[ExternalZipInstaller 
unzipTheFile] (self=0x68a8d60, _cmd=0x1483f3) at 
ExternalZipInstaller.mm:261 

代码:

#include <stdio.h> /* Standard input/output definitions */ 
#include <string.h> /* String function definitions */ 
#include <unistd.h> /* UNIX standard function definitions */ 
#include <fcntl.h> /* File control definitions */ 
#include <errno.h> /* Error number definitions */ 
#include <termios.h> /* POSIX terminal control definitions */ 

#ifndef O_BINARY 
#define O_BINARY 0 
#endif 
- (void) unzipTheFile 
{ 
    BOOL success = YES; 
    const char* filename = [self.zipName UTF8String]; 
    open(filename, O_RDONLY | O_BINARY); 
+0

什么是完整的堆栈跟踪?如果你在调用'open'之前调用'printf(“%s \ n”,filename)'会发生什么? –

+0

如果您将正确的文件名硬编码为字符串文字,会发生什么情况? –

+0

这不是很有帮助,printf:“/ Users/programmingstation7/Library/Application Support/iPhone Simulator/4.3/Applications/E2BD16DB-FFBA-45D2-B425-96C981380B85/Documents/issue2.zip”backtrace:'#0 0x002132dc in open () #1 0x000ddcec在 - [ExternalZipInstaller unzipTheFile](self = 0x68a8d60,_cmd = 0x1483f3)在ExternalZipInstaller.mm:261' – michael

回答

2

documentation为的NSString的UTF8字符串方法具有以下注释:

返回的C字符串只是作为返回的对象 将被释放自动释放;你应该复制C字符串,如果它需要存储 它在创建的C字符串为 的自动释放上下文之外。

我认为你需要将结果字符串复制到你自己的缓冲区而不是指向它。 ObjC垃圾回收器可能会从你的下面删除你的字符串。试试这个:

const char filename[MAX_PATH]; 
strcpy(filename, [self.zipName UTF8String], MAX_PATH); 
open(filename, O_RDONLY | O_BINARY); 
+0

只有当他打算在以后使用文件名时才会如此。在打开的调用点上,文件名缓冲区是有效的,并且至少在方法调用结束之前(就像autorelease一样)。 – aLevelOfIndirection