Retraction (matrix routine)

Jim Hester hester at ICSE.UCI.EDU
Wed Nov 20 12:07:20 AEST 1985


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



More information about the Comp.sources.unix mailing list