views:

84

answers:

1

Hey, guys, I am just starting to wrap my head around objective C and I am doing a little project on Iphone. And I just encountered a weird problem. I had to deal with images in my program so I have a lot local variables declared like temp[width][height]. If I am not using NSThread to perform image processing, it works all fine. However, if I use NSThread, it'll keep giving me EXC_BAD_ACCESS on whenever I try to access a 2-D array declared like temp[widht][height]. So I have to allocate memory from heap in order to have a 2-D array. That'll solve the problem but I still don't get it. My first thought would be stack over flow, but it worked all fine with one thread. I just don't get it.

A: 

It might be that the method to which the array is local terminates before the thread is finished with the array, so your array goes out of scope and the memory is occupied gets used for something else. But your thread doesn't know this and accesses the memory regardless.

invariant
Is there anyway do deal with that kinda problem? I am noob on multi-threading...
multithreading is very complicated, and there are a lot of issues to deal with (race conditions, deadlock, etc.)--you might want to read up on those. For this specific problem, you should allocate shared resources on the heap or, preferably, use objective-c objects such as NSArray (which are allocated on the heap anyways).
eman
Thanks folks! I found the problem. It was stack over flow. I created an 1-D array and tried to access to but still wasn't to. And then I made it smaller and it worked. I think either set the stack size by calling the method before adding the thread or allocate memory from the heap would make it work. Not sure by default how much stack memory was allocated for the thread.