mrueg
mrueg

Reputation: 8225

iPhone OS memory problem - how to debug?

I have a pretty weird problem in my iPhone app which is, I think, related to memory getting corrupted:

At one point, I need to sort an array, which I do with -[sortArrayUsingFunction].

The result is not correct unless I either allocate some memory with something like void *test = malloc(2 * sizeof( int )) before the method call or have, e.g., a call to NSLog() (which is never invoked) in the sorting function.

In other words: the sorting only works if I slightly increase the memory that was used before calling the sorting function. I think this is because at some point, memory gets corrupted.

How do you debug something like this?

Upvotes: 2

Views: 2123

Answers (3)

EricS
EricS

Reputation: 116

Try running your program in the simulator under Valgrind:

http://valgrind.org/

And how to use it under the simulator:

http://landonf.bikemonkey.org/code/iphone/iPhone_Simulator_Valgrind.20081224.html

You may have to change the VALGRIND path in the code example depending on where it gets installed.

Upvotes: 3

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

It sounds like some of your code is using already released objects. A lot of help with debugging this kind of errors is provided in Apple’s great Mac OS X Debugging Magic tech note, especially the foundation part.

For your case I'd disable autorelease pools (setting the environment variable NSEnableAutoreleasePool=NO) or use the zombie feature (NSZombieEnabled=YES) to find places where you send messages to released objects.

Upvotes: 3

Artelius
Artelius

Reputation: 49099

Such things can be a challenge to debug. There are some tools for detecting out-of-bounds accesses and such on other platforms, so I presume there would be something for the iPhone, however I don't know of any.

Perhaps you should store two copies of the array, and compare them for differences. Print out the differences. The nature of the "junk" that was introduced to one of the arrays might give a hint as to where it came from.

Also just go through the code that runs before this point, and re-read it (or better yet, get someone else to read it). You might spot a bug.

Upvotes: 0

Related Questions