[comp.lang.c] freeing mallocs

sven@cs.widener.edu (Sven Heinicke) (04/17/91)

question 26 of the FAQ is "How do I dynamically allocate a
multidimensional array?".  To deallocate a multidimensional array can
I just do a:

                free(array);

Or do I have to do this:

                for(i = 1;i < nrows; i++)
                    free(array[i]);
                free(array);


thanks.

-- 
sven@cs.widener.edu                                  Widener CS system manager
Sven Mike Heinicke                                          and Student
(pssmheinicke@cyber.widener.edu (if you must))

gordon@osiris.cso.uiuc.edu (John Gordon) (04/17/91)

	Freeing arrays depends on how you malloced them in the first place.
Did you allocate the thing as 1 big chunk, or element-by-element?

sven@cs.widener.edu (Sven Heinicke) (04/17/91)

In <1991Apr16.204927.19321@ux1.cso.uiuc.edu>, gordon@osiris.cso.uiuc.edu writes:
>
>	Freeing arrays depends on how you malloced them in the first place.
>Did you allocate the thing as 1 big chunk, or element-by-element?

I used the first method used in the FAQ list.


-- 
sven@cs.widener.edu                                  Widener CS system manager
Sven Mike Heinicke                                          and Student
(pssmheinicke@cyber.widener.edu (if you must))

barmar@think.com (Barry Margolin) (04/17/91)

In article <=-4_MX.@cs.widener.edu> sven@cs.widener.edu (Sven Heinicke) writes:
]question 26 of the FAQ is "How do I dynamically allocate a
]multidimensional array?".  To deallocate a multidimensional array can
]I just do a:
]
]                free(array);
]
]Or do I have to do this:
]
]                for(i = 1;i < nrows; i++)
]                    free(array[i]);
]                free(array);

Good rule of thumb: you should call free() as many times as you called
malloc().  This includes calls to malloc() that are done for you by library
routines.

Free(x) can only free as much stuff as was allocated by the call to
malloc() that returned x.

--
Barry Margolin, Thinking Machines Corp.

barmar@think.com
{uunet,harvard}!think!barmar