3

I've found an interesting way to allocate matrices in C which allows the use of [i][j] without initializing as double matrix_a[nrows][ncols]. The allocation is

double (*matrix_a)[ncols] = (double (*)[ncols])malloc(sizeof(double) * (nrows) * (ncols));

But I can't find how to properly free this type of allocation. Would it be as simple as free(matrix_a)?

Hayt
  • 5,210
  • 30
  • 37
mjswartz
  • 715
  • 1
  • 6
  • 19
  • What is unique in this allocation? Typical allocation+cast. – Revolver_Ocelot Sep 29 '16 at 12:37
  • It's unique only in the sense that I've never seen it before. I ran out of memory pretty quick allocating with `double matrix_a[nrows][ncols]` and found this style looking for more efficient methods. – mjswartz Sep 29 '16 at 12:40
  • You just allocated memory on the heap. `double a[m][n]` allocates on the stack, and stack is more limited than heap (typically). There is nothing special here. – Martin Nyolt Sep 29 '16 at 12:43
  • [do-i-cast-the-result-of-malloc?](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – LPs Sep 29 '16 at 12:51
  • OT: The cast isn't needed in C, nor is it recommended in any way. It's just useless. – alk Sep 29 '16 at 12:52
  • OT: Also it's more robust to instead of `sizeof(double) * (nrows) * (ncols)` use `nrows * sizeof *matrix_a`. – alk Sep 29 '16 at 12:54
  • @alk it had a C++ tag some time ago. In C++ you do cast the result of malloc. – Revolver_Ocelot Sep 29 '16 at 13:02
  • 1
    Better yet, use `malloc( sizeof(double[nrows][ncols]) )`. Self-documenting code is good code. – Lundin Sep 29 '16 at 13:06
  • Also this code probably won't work well in C++, since C++ doesn't have VLA:s yet. You'd have to use compile-time constants. – Lundin Sep 29 '16 at 13:08

1 Answers1

6

That is correct. You may only pass to free what was returned from malloc and family. So since you did one malloc, you do one free.

Also, there is no need to cast the return value of malloc:

double (*matrix_a)[ncols] = malloc(sizeof(double) * (nrows) * (ncols));
Community
  • 1
  • 1
dbush
  • 205,898
  • 23
  • 218
  • 273
  • If I remove the cast, I get `error: invalid conversion from ‘void*’ to ‘double (*)[ncols]’ [-fpermissive]` – mjswartz Sep 29 '16 at 14:07
  • 1
    @mjswartz That's because you're compiling with a C++ compiler, not a C compiler. C++ does require the cast. – dbush Sep 29 '16 at 15:07