2D array in C - Implimenting with malloc

Status
Not open for further replies.

sryan2k1

Ars Legatus Legionis
46,879
Subscriptor++
Hey All,

I've got a problem with some C we are working on (embedded systems), right now we have a huge 2D array that works fine, it looks like this

Code:
t_ourStructType Array[SIZE1][SIZE2];

I need to convert that to use our lightweight memory allocator, (effectively just malloc with some RTOS specific stuff added in)


C pointers always hurt my head but I can't figure this one out, I effectively need to say

Code:
t_ourStructType *Array;

Array = _mem_alloc(sizeof(ourStructType * SIZE1 * SIZE2));


But then I have no idea how to have code index into the array properly. Is it possible at that point to still index items directly (Array[x][y]) or will array operations have to go through a reader/writer function that needs to be built?


Many Thanks!



For those who want more info, it's a embedded system with 64K of RAM, and this array is about 10K that gets statically assigned by the linker, we need to move it to the lightweight allocator which will allow that RAM space to be used for something else when the task that is using this memory is shut down.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
You have several choices:

Option 1 - Allocate the array piecemeal:
Code:
T **arr = malloc(SIZE1 * sizeof *arr); // allocates a SIZE1-array of pointer to T.
if (arr)
{
  int i;
  for (i = 0; i < SIZE2; i++)
  {
    int j;
    arr[i] = malloc(SIZE2 * sizeof *arr[i]); // allocates a SIZE2-array of T.
    for (j = 0; j < SIZE2; j++)
    {
      arr[i][j] = some_initial_value();
    }
  }
}

Pros: you can index arr just like any 2-d array. Cons: memory is not allocated contiguously, which for what you're doing may be a problem.

Option 2 - allocate the memory as a 1-d array, compute index:
Code:
T *arr = malloc(SIZE1 * SIZE2 * sizeof *arr);
int i;
for (i = 0; i < SIZE1; i++)
{
  int j;
  for (j = 0; j < SIZE2; j++)
  {
    arr[i*SIZE1 + j] = some_initial_value();
  }
}

Pros: memory is contiguously allocated. Cons: doesn't act like a 2-d array.

Option 3 - allocate a 1-d array for your data and a second 1-d array of pointers into that data:
Code:
T *heap = malloc(SIZE1 * SIZE2 * sizeof *arr);
T *arr[SIZE1];
int i;
for (i = 0; i < SIZE1; i++)
{
  arr[i] = &heap[i*SIZE2];
}

for (i = 0; i < SIZE1; i++)
{
  int j;
  for (j = 0; j < SIZE2; j++)
  {
    arr[i][j] = some_initial_value();
  }
}

Pros: Contiguous memory, plus 2-d array semantics. Cons: overhead of second array.

Option 4 - Allocate a pointer to an array:
Code:
T (*arr)[SIZE2] = malloc(SIZE1 * sizeof *arr);
{
  int i;
  for (i = 0; i < SIZE1; i++)
  {
    int j;
    for (j = 0; j < SIZE2; j++)
    {
      arr[i][j] = some_initial_value();
    }
  }
}

Pros: contiguously allocated memory, access as 2-d array. Cons: if you're not using a C99 compiler, SIZE2 will have to be known at compile time.

Note that if you have to pass this array to a function, the prototypes will have to look like
Code:
void foo(T **arr)         // for option 1
void foo(T *arr)          // for option 2
void foo(T **arr)         // for option 3
void foo(T (*arr)[SIZE2]) // for option 4
 

sryan2k1

Ars Legatus Legionis
46,879
Subscriptor++
Because a lot of the system relies on the lightweight memory allocator (effectively malloc with some OS awareness added in for the RTOS it's running in).


The "lightweight memory pool" is everything left over on the heap that isn't assigned at link time. Also, Tasks + Stack are created from the lightweight pool, with their resources being freed either manually, or when the task exits.


If I say
Code:
#include "bits.h"

char stuff[512];

void DoStuff()
{
    Stuff;
}
That 512 bytes will never be available to anything else since the linker pre-allocates it, regardless of it's use or not.


However if we do
Code:
char *stuff;

void MoreStuff()
{
    stuff = _alloc(512);
    //things with stuff
    _mem_free(stuff);
}

I am only using 4 bytes for the pointer, and the actual "stuff" block of RAM is available to go (back) into the pool for anything else that wants it.
 
There's a syntax I found online about a year ago when working on a project in C for allocating multi-dimensional arrays dynamically using a pointer to a multidimensional array. I'd never seen it before and don't know if it's standard C (I vaguely remember the post saying it was a C99 thing, and I think it was on Stack Overflow, but I wasn't able to find it again with a few quick searches just now), but it worked on GCC on Windows and *nix and Clang on Linux.

Code:
// To declare and initialize
char (*stuff)[SIZE1][SIZE2] = (char(*)[SIZE1][SIZE2])malloc(sizeof(char) * SIZE1 * SIZE2);

// To acces
(*stuff)[x][y] = whatever;

It was certainly much more convenient and concise than the for loop version (especially since I was doing a three dimensional array), but I've pretty much never seen it elsewhere so I'm curious about just how supported/official it is.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
Stupendous Man":2ci7u1hs said:
There's a syntax I found online about a year ago when working on a project in C for allocating multi-dimensional arrays dynamically using a pointer to a multidimensional array. I'd never seen it before and don't know if it's standard C (I vaguely remember the post saying it was a C99 thing, and I think it was on Stack Overflow, but I wasn't able to find it again with a few quick searches just now), but it worked on GCC on Windows and *nix and Clang on Linux.

Code:
// To declare and initialize
char (*stuff)[SIZE1][SIZE2] = (char(*)[SIZE1][SIZE2])malloc(sizeof(char) * SIZE1 * SIZE2);

// To acces
(*stuff)[x][y] = whatever;

It was certainly much more convenient and concise than the for loop version (especially since I was doing a three dimensional array), but I've pretty much never seen it elsewhere so I'm curious about just how supported/official it is.

It's standard vanilla C, although I'd rewrite it as
Code:
char (*stuff)[SIZE1][SIZE2] = malloc(sizeof *stuff); // you shouldn't cast the result of malloc,
                                                     // and you can apply the sizeof operator
                                                     // to the target expression

Like I said above, the main drawback is that if you're not using a C99 compiler, both SIZE1 and SIZE2 must be compile-time constants. That and you have to explicitly dereference the pointer, whereas if you do something like
Code:
char (*stuff)[SIZE2] = malloc(SIZE1 * sizeof *stuff);

the type of the expression stuff is "pointer to SIZE2-element array of char", and since stuff[0] == *(stuff + 0) == *stuff, the type of the expression stuff is "SIZE2-element array of char", so you can write stuff[j] instead of (*stuff)[j].

Either way, memory is allocated contiguously.
 

fitten

Ars Legatus Legionis
55,634
Subscriptor++
Yeah, if the stack can handle it, though, IMO that's the best way (put it inside a function as the above example). Using that method, it should allocate easily. If you're using allocation/free, depending on your system, you may not get the same block every time (likely won't anyway) due to fragmentation and other effects. Eventually, you can run out of memory if the app is a TSR type and your system doesn't have great process management (where it can completely clean up the process every time).
 
jbode":2cdd9rbc said:
It's standard vanilla C, although I'd rewrite it as
Code:
char (*stuff)[SIZE1][SIZE2] = malloc(sizeof *stuff); // you shouldn't cast the result of malloc,
                                                     // and you can apply the sizeof operator
                                                     // to the target expression

Like I said above, the main drawback is that if you're not using a C99 compiler, both SIZE1 and SIZE2 must be compile-time constants. That and you have to explicitly dereference the pointer, whereas if you do something like
Code:
char (*stuff)[SIZE2] = malloc(SIZE1 * sizeof *stuff);

the type of the expression stuff is "pointer to SIZE2-element array of char", and since stuff[0] == *(stuff + 0) == *stuff, the type of the expression stuff is "SIZE2-element array of char", so you can write stuff[j] instead of (*stuff)[j].

Either way, memory is allocated contiguously.


Thanks for the info (and the code cleanup tips), I didn't realize that in non-C99 compilers the sizes would have to be constant, so I was wondering why I hadn't seen it in other C references as a simpler alternative to for loops. And I guess if you are using C99 (and have the stack space) you don't need to use it much because you can just locally declare that array on the stack even with not-known-at-compile-time sizes.
 
Status
Not open for further replies.