Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!apple!heksterb From: heksterb@Apple.COM (Ben Hekster) Newsgroups: comp.sys.mac.programmer Subject: Re: Using Malloc to create variables. help? Message-ID: <48214@apple.Apple.COM> Date: 17 Jan 91 18:14:08 GMT References: <6996@crash.cts.com> Organization: Apple Computer Inc., Cupertino, CA Lines: 37 You write: extern int **map; if ( (map = (int **)( malloc( (100 * 100) * sizeof(int) + 1 ) )) == NULL) ExitToShell(); map[x][y] = -1; Well, for one thing, malloc returns pointers to nonrelocatable blocks, not handles. Since arrays and pointer types are equivalent in C, the compiler interprets `map' as an array of pointers to arrays of int. Although the variables are declared incorrectly, the access `map[x][y] = -1' is correct. My guess is that the compiler you use employs 2-byte ints, and since pointers are 4 bytes in the Macintosh world, the array accesses are therefore writing twice as much stuff into memory as you expect (0xffffffff rather than 0xffff) so you end up stepping all over the Memory Manager data structures. You can go two ways--either stick with C's malloc-type allocation, or use the Memory Manager NewHandle calls. Obviously the Memory Manager stuff is a little friendlier since it gives the system a chance to juggle memory when it gets tight. By the way, what is the `+ 1' for in your malloc? Paranoia?? If so, I'd suggest taking it out because otherwise it's a great way of hiding bugs in your algorithms. You *do* want to find bugs, don't you? If you haven't got it yet, I strongly recommend buying Kernighan & Ritchie's "The C Programming Language". An excellent book that will teach you everything you need to know and renders everything else obsolete. _______________________________________________________________________________ Ben Hekster | "I've had my fun Student intern | but now it's time AppleLink: heksterb | to serve your conscience Internet: heksterb@apple.com | overseas" BITNET: heksterb@henut5 | --Orange Crush, R.E.M. (Green)