I’m getting an EXC_BAD_ACCESS error, and It’s because of this part of code. Basically, I take an input and do some work on it. After multiple inputs, it throws the error. Am I doing something wrong with my memory here? I’d post the rest of the code, but it’s rather long — and I think this may be where my problem lies (It’s where Xcode points me, at least).
-(IBAction) findShows: (id) clicked
{
char urlChars[1000];
[self getEventURL: urlChars];
NSString * theUrl = [[NSString alloc] initWithFormat:@"%s", urlChars];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:theUrl]];
int theLength = [data length];
NSString *content = [NSString stringWithUTF8String:[data bytes]];
char eventData[[data length]];
strcpy(eventData, [content UTF8String]);
[self parseEventData: eventData dataLength: theLength];
[whatIsShowing setStringValue:@"Showing events by this artist"];
}
When a crash occurs, there will be a backtrace.
Post it.
Either your program will break in the debugger, and the call stack will be in the debugger UI (or you can type ‘bt
With that, the cause of the crash is often quite obvious. Without that, we are left to critique the code.
So, here goes….
This is, at best, a security hole and, at worst, the source of your crash. Any time you are going to copy bytes into a buffer, there should be some kind of way to (a) limit the # of bytes copied in (pass the length of the buffer) and (b) the # of bytes copied is returned (0 for failure or no bytes copied).
Given the above, what happens if there are 1042 bytes copied into
urlCharsbygetEventURL:? boomThis is making some assumptions about
urlCharsthat will lead to failure. First, it assumes thaturlCharsis of a proper%scompatible encoding. Secondly, it assumes thaturlCharsis NULL terminated (and didn’t overflow the buffer).Best to use one of the various NSString methods that create strings directly from the buffer of bytes using a particular encoding. More precise and more efficient.
I hope this isn’t on the main thread… ’cause it’ll block if it is and that’ll make your app unresponsive on slow/flaky networks.
This is about the least efficient possible way of doing this. There is no need to create an
NSStringinstance just to then turn it into a(char *). Just grab thebytesfrom the data directly.Also — are you sure that the data returned is NULL terminated? If not, that
strcpy()is gonna blow right past the end of youreventDatabuffer, corrupting the stack.What kind of data are you parsing that you really want to parse the raw bytes? In almost all cases, such data should be of some kind of structured type; XML or, even, HTML. If so, there is no need to drop down to parsing the raw bytes. (Not that raw data is unheard of — just odd).