michael
michael

Reputation: 2342

EXC_BAD_ACCESS, standard c library "open" on iphone?

Pretty straightforward question,

no matter what I do the app crashes on attempting to call open(), below is a part of the code that is relevant. filename is not a garbage value, and contains an absolute path to the file. This fails on the device and the simulator.

printf of filename returns:

/Users/programmingstation7/Library/Application Support/iPhone Simulator/4.3/Applications/E2BD16DB-FFBA-45D2-B425-96C981380B85/Documents/issue2.zip

relevant backtrace:

#0 0x002132dc in open () 

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

code:

#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);

Upvotes: 1

Views: 334

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67509

The documentation for the UTF8String method of NSString has the following note:

The returned C string is automatically freed just as a returned object would be released; you should copy the C string if it needs to store it outside of the autorelease context in which the C string is created.

I think you need to copy the resulting string into your own buffer instead of just pointing to it. The ObjC garbage collector could be deleting your string from under you. Try this instead:

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

Upvotes: 2

Related Questions