473,398 Members | 2,212 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

2D arrays and malloc

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 no****@mega-nerd.com (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
Nov 14 '05 #1
2 2299
Erik de Castro Lopo wrote:

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?
Yes.
Can anybody point me to the relevant section
of the C standard.
'a' is a pointer to an array.
#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);
/* This is the way we usually write something like that, here: */
a = malloc(N * sizeof *a);

/*
** I find it simpler to post a rudimentary success check,
** rather than to explain why it's missing from the code:
*/
if (a == NULL) {
fputs("malloc problem\n", stderr);
exit(EXIT_FAILURE);
}
for (j = 0 ; j < M ; j++)
for (k = 0 ; k < N ; k++)
a [j][k] = j * k + j;

free(a);

return 0 ;
}


I think it would have been more natural
to associate k with M and j with N,
but in terms of size and alignment, everything is OK anyway.

--
pete
Nov 14 '05 #2
On Fri, 17 Dec 2004 23:10:18 +1100, Erik de Castro Lopo
<no****@mega-nerd.com> wrote:
<snip>
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. <snip> { double (*a)[M] ;
a = malloc (sizeof (double) * N * M);

<snip>

Yes. You don't need the standard; see FAQ 6.16 et seq at usual places
and http://www.eskimo.com/~scs/C-faq/top.html .

The pointer to (allocated) pointers to (allocated) elements isn't
actually a 2D array at all, but a 2-level structure that can be
subscripted (used) as if it were a 2D array; that was/is the only way
to make both dimensions variable in C89, and still the only way for a
static (including global) variable in C99.

Even so it doesn't actually require a _loop_ of malloc's (and free's),
although that is a direct way and easy to remember; you can malloc
once for the row-pointers and once for all rows (unless that's so
large it exceeds a limit on your system) -- and if the elements are
characters (which cannot require nontrivial alignment) you can even
tack them onto the row pointers into a single block. Again see 6.16.

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: csx | last post by:
Hi everyone! two quick questions relating to arrays. Q1, Is it possible to re-assign array elements? int array = {{2,4}, {4,5}}; array = {2,3}
10
by: Ian Todd | last post by:
Hi, I am trying to read in a list of data from a file. Each line has a string in its first column. This is what i want to read. I could start by saying char to read in 1000 lines to the array( i...
2
by: Morgan | last post by:
Thanks to all of you because I solved the problem related with my previous post. I simply made confusion with pointers to pointers and then succeeded passing the reference to the first element...
8
by: masood.iqbal | last post by:
All this time I was under the illusion that I understand the concept of multi-dimensional arrays well ---- however the following code snippet belies my understanding. I had assumed all along...
15
by: Paul Morrison | last post by:
Hi all, I need to come up with some differences between arrays in Java and C, I have searched Google and so far all I have found is the following: Arrays in Java are reference types with...
11
by: truckaxle | last post by:
I am trying to pass a slice from a larger 2-dimensional array to a function that will work on a smaller region of the array space. The code below is a distillation of what I am trying to...
39
by: Martin Jørgensen | last post by:
Hi, I'm relatively new with C-programming and even though I've read about pointers and arrays many times, it's a topic that is a little confusing to me - at least at this moment: ---- 1)...
38
by: djhulme | last post by:
Hi, I'm using GCC. Please could you tell me, what is the maximum number of array elements that I can create in C, i.e. char* anArray = (char*) calloc( ??MAX?? , sizeof(char) ) ; I've...
2
by: Dr Dav | last post by:
Hello all, I'm a physicist whose rewriting a numerical simulation, previously written in IDL, in C with the goal reducing runtime. As you may imagine, my C programming skills are quite poor but I...
35
by: Andrew Fabbro | last post by:
I have a need to create an array that is larger than size_t - 1, which I believe is the largest guaranteed array. I though I'd found salvation in FAQ 6.14, but it appears I am not understanding...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.