Re: How to free dynamically allocated array?



Krishanu Debnath wrote:
Markus wrote:

Hi,

I have read the FAQ 6.16 on how to dynamically allocate a
two-dimensional array.

I do it like this:

double** A = (double **)malloc(m * sizeof(double *));

This is not the preferred form and is error prone. Try double** A = malloc(m * sizeof *A);

Reasons for this include:
   Getting rid of the cast means that all compilers (including C89
   compilers are *required* to produce a diagnostic if you forget to
   include stdlib.h

   By only specifying the type once you only have to get it right once
   rather than in the three places you specified type. Think of the risk
   of miscounting the *s if you did a 5D array!

   It is less to type.

   It is less to read

The FAQ at http://www.eskimo.com/~scs/C-faq/q6.16.html is out of date in this.

Also you need to check if malloc succeeded before you use the space you hope was allocated. After all, where will the code below write if malloc failed?

for(i = 0; i < m; i++)
   A[i] = (double *)malloc(n * sizeof(double));

A[i] = malloc(n * sizeof *A[i]);

See above.

But how do I free it? I currently have only

free(A);

but I guess it is not enough.

Correct. Each successful call to malloc needs a corresponding free.

The FAQ is not clear about this.

OK, you read the FAQ which is good. You told us that you had read this section which is even better. It's nice to see evidence that some people do the right thing.


for(i = 0; i < m; i++)
    free(A[i]);
free(A);

This is correct. -- Flash Gordon Living in interesting times. Although my email address says spam, it is real and I read it. .



Relevant Pages

  • Re: How to free dynamically allocated array?
    ... >> Markus wrote: ... >>>I have read the FAQ 6.16 on how to dynamically allocate a ... where will the code below write if malloc ...
    (comp.lang.c)
  • Re: A quick question
    ... In all the compilers that I've used the ... int main ... They all should have identical behavior, but execution ... C++ Faq: http://www.parashift.com/c++-faq-lite ...
    (comp.lang.c)
  • Re: exe to C++ source code
    ... Many compilers, which compile to different ... platform specific instructions. ... C++ Faq: http://www.parashift.com/c++-faq-lite ...
    (comp.lang.cpp)
  • Re: Learning borland.
    ... The current faq make the point several times that implementation ... there are a number of compilers out there. ... some of the common compilers to get a hello world program running ... It would be useful to start a conversation about topicality, ...
    (alt.comp.lang.learn.c-cpp)
  • Re: How to free dynamically allocated array?
    ... Markus wrote: ... > two-dimensional array. ... > The FAQ is not clear about this. ...
    (comp.lang.c)