Releasing entryDate in dealloc causes memory error


#1

In the section “dealloc” the dealloc method is added to the implementation of LotteryEntry. After doing this, a malloc error is reported by the debugger, after leaving the autoreleasepool block in main.m: lottery(4121,0x7fff7e695180) malloc: *** error for object 0x10011bbb0: pointer being freed was not allocated

After some debugging, I found that this was caused by the statement “[ entryDate release ];” in the dealloc method of LotteryEntry. Which is understandable, since entryDate is set as the parameter of method initWithEntryDate:, which is called from main.m with parameter iWeeksFromNow, which is not an allocated object:
NSDate *iWeeksFromNow = [ cal dateByAddingComponents:weekComponents toDate:now options:0 ];

After removing the line “[ entryDate release ];” in the dealloc method of LotteryEntry the malloc error was not any more occurring.

Is this is mistake in the book, or is there a change in Mountain Lion causing this (I run OS X 10.8.2), or did I make a mistake somewhere?


#2

Did you forget to retain the date passed in to -initWithEntryDate:? You should have this line in that method:

Adam


#3

Thanks for helping me: I had made a mistake at that line. In my LotteryEntry.m I had entered:

-( id )initWithEntryDate:(NSDate *)theDate {
self = [ super init ];
if ( self ) {
NSAssert( theDate != nil, @“Argument must be non-nil” );
[color=#FF0000][ entryDate retain ];[/color]
entryDate = theDate;
firstNumber = ( ( int )random( ) % 100 ) + 1;
secondNumber = ( ( int )random( ) % 100 ) + 1;
}
return self;
}

So this would have caused my memory problem.