E
Erik de Castro Lopo
Hi all,
I found the following malloc/free example on a mailing list and immediately
thought it was wrong. So, I whipped up the following test program, compiled
it on Linux with gcc and used "-W and -Wall -ansi -pedantic". Gcc did not
complain. I then ran the executable under valgrind (a Linux memory checker
much like Purify) and it reported no errors.
I always remember 2D arrays requiring an outer malloc followed by a loop
which mallocs the second dimension and something similar for free.
So, is the following code legal? Can anybody point me to the relevant section
of the C standard.
#include <stdio.h>
#include <stdlib.h>
#define M 8
#define N 12
int
main (void)
{ double (*a)[M] ;
unsigned j, k ;
a = malloc (sizeof (double) * N * M);
for (j = 0 ; j < M ; j++)
for (k = 0 ; k < N ; k++)
a [j][k] = j * k + j;
free(a);
return 0 ;
}
--
+-----------------------------------------------------------+
Erik de Castro Lopo (e-mail address removed) (Yes it's valid)
+-----------------------------------------------------------+
"Lumping configuration data, security data, kernel tuning parameters,
etc. into one monstrous fragile binary data structure is really dumb."
- David F. Skoll
I found the following malloc/free example on a mailing list and immediately
thought it was wrong. So, I whipped up the following test program, compiled
it on Linux with gcc and used "-W and -Wall -ansi -pedantic". Gcc did not
complain. I then ran the executable under valgrind (a Linux memory checker
much like Purify) and it reported no errors.
I always remember 2D arrays requiring an outer malloc followed by a loop
which mallocs the second dimension and something similar for free.
So, is the following code legal? Can anybody point me to the relevant section
of the C standard.
#include <stdio.h>
#include <stdlib.h>
#define M 8
#define N 12
int
main (void)
{ double (*a)[M] ;
unsigned j, k ;
a = malloc (sizeof (double) * N * M);
for (j = 0 ; j < M ; j++)
for (k = 0 ; k < N ; k++)
a [j][k] = j * k + j;
free(a);
return 0 ;
}
--
+-----------------------------------------------------------+
Erik de Castro Lopo (e-mail address removed) (Yes it's valid)
+-----------------------------------------------------------+
"Lumping configuration data, security data, kernel tuning parameters,
etc. into one monstrous fragile binary data structure is really dumb."
- David F. Skoll