Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site brl-tgr.ARPA Path: utzoo!watmath!clyde!bonnie!akgua!gatech!seismo!brl-tgr!tgr!hester@ICSE.UCI.EDU From: hester@ICSE.UCI.EDU (Jim Hester) Newsgroups: net.sources Subject: Re: Retraction (matrix routine) Message-ID: <3419@brl-tgr.ARPA> Date: Tue, 19-Nov-85 21:07:20 EST Article-I.D.: brl-tgr.3419 Posted: Tue Nov 19 21:07:20 1985 Date-Received: Thu, 21-Nov-85 07:16:39 EST Sender: news@brl-tgr.ARPA Lines: 49 Re your code to make a pointer-vector matrix: > char *valloc (); > > double **make_mat (m, n) > { > double **result; > int i; > > result = (double **)valloc (m * (n + 1)); > for (i = 0; i < m; i++) > *(result + i) = (double *)result + m + i * n; > return (result); > } and your reply to my comments on that code: > Thanks for pointing out my error. Pointers are not the same size as > doubles on my system (pointers 4 bytes, doubles 8) so I'm not sure why > it worked for me. I'll check it sometime and see what was going on. Curious myself to know why it worked, I looked up the definition of valloc (I've never used it), and it partially answers the problem. The rest of the reason comes from a bit of luck. Valloc returns space beginning on a page boundry by calling malloc with a bloated size to force a new page to be allocated, so you get at least a page of memory actually allocated. You only asked for n bytes for pointers (1/4 of what you need) and m*n bytes for double storage (1/8 of what you need) but, for small tests, the extra space on a page would be enough to avoid errors. In allocating the rows, result is massaged to type (double *), which makes the associated arithmetic specify enough space for the true size of doubles. Thus, for the vector of pointers, you allocate m elements the size of doubles: twice what you need for the pointers. Although the vector of pointers is larger than needed, no error occurs since the extra space is just never accessed when your other programs later access this space as pointers and the wasted space is also absorbed by the full page allocation. I believe that, in a moderately large case, the factors of 4 and 8 would catch up with you and you would get errors due to referencing memory outside of that which was allocated. Interesting case. Thanks for the puzzle, and giving me a reason to look up valloc. I'd never heard of it before. Jim