Re: How to free dynamically allocated array?
- From: Flash Gordon <spam@xxxxxxxxxxxxxxxxxx>
- Date: Tue, 30 Aug 2005 15:15:04 +0100
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. .
- Follow-Ups:
- Re: How to free dynamically allocated array?
- From: Markus
- Re: How to free dynamically allocated array?
- References:
- How to free dynamically allocated array?
- From: Markus
- Re: How to free dynamically allocated array?
- From: Krishanu Debnath
- How to free dynamically allocated array?
- Prev by Date: Re: How to free dynamically allocated array?
- Next by Date: Re: understanding format specifiers
- Previous by thread: Re: How to free dynamically allocated array?
- Next by thread: Re: How to free dynamically allocated array?
- Index(es):
Relevant Pages
|