[comp.sys.mac.programmer] Think C Agony! -- Shape-of-memory problem

tim@hoptoad.uucp (Tim Maroney) (03/11/91)

In article <1991Mar7.063549.14081@dartvax.dartmouth.edu>
sean@eleazar.dartmouth.edu (Sean P. Nolan) writes:
>The following code, run without the Think Debugger, crashes with an addr error
>at the (**hclusterNew).LearningRate = (**network).DefaultBiasLearningRate
>assignment. Now here's the trick. Put in a Debugger() command right before
>the assignment, and both handles (hclusternew and network) are perfectly
>valid, and no crash occurs! Take away the Debugger(), and there's a
>reproducible crash. Also, the same code run under the Think Debugger does
>not crash. Help!
>
>	if (!((**hclusterNew).prgbiasstruct =
>		(BIASSTRUCT**) NewHandle(NumNodes * sizeof(BIASSTRUCT))))

This is an illegal assignment.  The address of the target on the left
hand is already computed before the NewHandle call is made.  The
NewHandle call may move memory.  If it does, suddenly you are assigning
into outer space.  Assign into a temporary variable, then into
(**hclusterNew).prgbiasstruct.

The bizarre results you are seeing are almost always a sign of this
kind of shape-of-memory bug.  By adding a Debugger call or running in a
different environment, you change the shape of memory, that is, the
relation of blocks to each other in the heap.  With two more bytes in
your CODE resource, the relationship changes so that the NewHandle
won't move memory.

MacsBug's Heap Scramble mode is a good way to test code for this kind
of unpleasantness.

Oh, almost missed my cue --

IT'S A COMPILER BUG!

Not really, since C compilers are allowed to evaluate assignments in
any order.  However, it's a bad design decision in a Mac compiler to do
it left-first.  If the language definition gives you a choice of two
ways to do something, and on a particular machine one way causes weird
and hard-to-find bugs and the other is perfectly fine, then it doesn't
take a Dijkstra to figure out which road to toodle down.
-- 
Tim Maroney, Mac Software Consultant, sun!hoptoad!tim, tim@toad.com

"And did you ever stop to think that Tim may be doing something right by being
 so controversial?  I mean, he may be an asshole but at least he's an 
 intelligent asshole.  I do have to admit his articles tend to entertain me,
 although I kill the resulting flame wars." -- maxc1142@ucselx.sdsu.edu