help needed about dynamic space allocation

Wayne Throop throopw at dg_rtp.UUCP
Wed Nov 26 08:29:23 AEST 1986


> fano at lifia.UUCP (Rampa*)
> I need advice on dynamic space allocation for multidimensionnal arrays:

Well...  a little maybe.

>   float **sig;                          /* matrix declaration     */
>   sig = (int *)malloc(n * sizeof(int)); /* allocates space for sig */

OK.  Stop right here for a minute.  What's wrong with this picture?  It
is a little subtle, perhaps, but a pointer value of type (int *) is
being assigned to a pointer of type (float **).  Does anybody really not
see anything wrong with this?  Hmmmmmm?  Can you say "illegal pointer
combination"?  I knew you could.  Lint can say it too.  Let's say it
together, boys and girls...  (oh all right, I know I'm being nasty...
I'll behave myself the rest of the posting, alright?)

To fix this, make the allocation read:

        sig = (float **)malloc(n * sizeof(float *));

>       sig[i] = (float *)malloc(n * sizeof(float)); /* allocate a column */

This one is already correct.

>       free(sig[i]);           /* desallocates space     */

Should be: free((char *)sig[i]);

>   free(sig);

Should be: free( (char *)sig );

> during the compiling time, I get the following warning:
>      "combin1.c", line 220: warning: illegal pointer combination
> any-way the program runs, and gives the desired results.

The program will run correctly on systems where integers have the same
length as pointers to float, and where pointers to float have the same
format as pointers to char.  I don't know what kind of system that would
be.  Maybe... oh, I don't know... could it be... *A* *VAX*????  (Isn't
that special? :-)

> The compiler message suggests that I didn't use the proper way to implement
> matrix dynamic allocation. So, could someone over there give me advices for
> a cleaner solution.

In fact, the program seemed quite clean and well written already, except
for the pointer type mismatches and the hidden assumption about the size
of floats and ints.  Fix that, and the program should still work, and
lint will shut up also... who could ask for more?

--
A programming language is low level when its programs require attention
to the irrelevant.
                                --- Alan J. Perlis
-- 
Wayne Throop      <the-known-world>!mcnc!rti-sel!dg_rtp!throopw



More information about the Comp.lang.c mailing list