4

So I am learning how to program in C, and am starting to learn about dynamic memory allocation. What I know is that not all the time will your program know how much memory it needs at run time.

I have this code:

#include <stdio.h>

int main() {
   int r, c, i, j;
   printf("Rows?\n");
   scanf("%d", &r);
   printf("Columns?\n");
   scanf("%d", &c);

   int array[r][c];
   for (i = 0; i < r; i++)
      for (j = 0; j < c; j++)
         array[i][j] = rand() % 100 + 1;

   return 0;
}

So if I wanted to create a 2D array, I can just declare one and put numbers in the brackets. But here in this code, I am asking the user how many rows and columns they would like, then declaring an array with those variables, I then filled up the rows and columns with random integers.

So my question is: Why don't I have to use something like malloc here? My code doesn't know how many rows and columns I am going to put in at run time, so why do I have access to that array with my current code?

3
  • "My code doesn't know how many rows and columns I am going to put in at run time" --> it does know when the variable length array is declared. May 25, 2020 at 3:06
  • Yes I was confused between run time and compile time. Thanks for the clarification May 25, 2020 at 3:12
  • 2D array seg fault in C worth a read for background on the difference between declaring and handling array and allocating for objects created with a pointer-to-pointer-to-type to simulate a 2D array. May 25, 2020 at 6:46

5 Answers 5

6

So my question is: why don't I have to use something like malloc here? My code doesn't know how many rows and columns I am going to put in at run time, so why do I have access to that array with my current code?

You are using a C feature called "variable-length arrays". It was introduced in C99 as a mandatory feature, but support for it is optional in C11 and C18. This alternative to dynamic allocation carries several limitations with it, among them:

  • because the feature is optional, code that unconditionally relies on it is not portable to implementations that do not support the feature

  • implementations that support VLAs typically store local VLAs on the stack, which is prone to producing stack overflows if at runtime the array dimension is large. (Dynamically-allocated space is usually much less sensitive to such issues. Large, fixed-size automatic arrays can be an issue too, but the potential for trouble with these is obvious in the source code, and it is less likely to evade detection during testing.)

  • the program still needs to know the dimensions of your array before its declaration, and the dimensions at the point of the declaration are fixed for the lifetime of the array. Unlike dynamically-allocated space, VLAs cannot be resized.

  • there are contexts that accommodate ordinary, fixed length arrays, but not VLAs, such as file-scope variables.

2
  • 1
    I think, allocating large fixed size arrays on the stack will be prone to stack overflows the same way as dynamically sized arrays. It seems, you are assuming that variable-length arrays inherently have a tendency to be significantly larger than fixed size arrays and that typical C programs are otherwise economical with the stack memory.
    – Holger
    May 25, 2020 at 9:03
  • Yes, @Holger, large, fixed-size automatic arrays can be a problem too, but in practice they are much less of one. Variable-length arrays don't necessarily have a tendency to be large; rather, they have a greater risk of unexpectedly turning out to be too large. Too-large fixed-size arrays are more easily caught during testing. I have added a few words to clarify. May 25, 2020 at 11:24
1

Your array is allocated on the stack, so when the function (in your case, main()) exits the array vanishes into the air. Had you allocated it with malloc() the memory would be allocated on the heap, and would stay allocated forever (until you free() it). The size of the array IS known at run time (but not at compile time).

4
  • Ah I guess I was a little confused between run time and compile time. May 25, 2020 at 3:10
  • When you say exists forever, what does that mean? If I use malloc, it is in my computer memory forever or until I free it? May 25, 2020 at 3:11
  • @c_help123 Until you free it, just as the answer says :)
    – Igor Rivin
    May 25, 2020 at 3:16
  • 1
    until you free() it, and as long as your program is still running. Un-freed "malloced" memory is automatically freed (in most OS's) when the program exits.
    – TonyB
    May 25, 2020 at 3:50
1

In your program, the array is allocated with automatic storage, aka on the stack, it will be released automatically when leaving the scope of definition, which is the body of the function main. This method, passing a variable expression as the size of an array in a definition, introduced in C99, is known as variable length array or VLA.

If the size is too large, or negative, the definition will have undefined behavior, for example causing a stack overflow.

To void such potential side effects, you could check the values of the dimensions and use malloc or calloc:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int r, c, i, j;

    printf("Rows?\n");
    if (scanf("%d", &r) != 1)
        return 1;
    printf("Columns?\n");
    if (scanf("%d", &c) != 1)
        return 1;

    if (r <= 0 || c <= 0) {
        printf("invalid matrix size: %dx%d\n", r, c);
        return 1;
    }
    int (*array)[c] = calloc(r, sizeof(*array));
    if (array == NULL) {
        printf("cannot allocate memory for %dx%d matrix\n", r, c);
        return 1;
    }
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            array[i][j] = rand() % 100 + 1;
        }
    }
    free(array);
    return 0;
}

Note that int (*array)[c] = calloc(r, sizeof(*array)); is also a variable length array definition: array is a pointer to arrays of c ints. sizeof(*array) is sizeof(int[c]), which evaluates at run time to (sizeof(int) * c), so the space allocated for the matrix is sizeof(int) * c * r as expected.

0

The point of dynamic memory allocation (malloc()) is not that it allows for supplying the size at run time, even though that is also one of its important features. The point of dynamic memory allocation is, that it survives the function return.

In object oriented code, you might see functions like this:

Object* makeObject() {
    Object* result = malloc(sizeof(*result));
    result->someMember = ...;
    return result;
}

This creator function allocates memory of a fixed size (sizeof is evaluated at compile time!), initializes it, and returns the allocation to its caller. The caller is free to store the returned pointer wherever it wants, and some time later, another function

void destroyObject(Object* object) {
    ...  //some cleanup
    free(object);
}

is called.

This is not possible with automatic allocations: If you did

Object* makeObject() {
    Object result;
    result->someMember = ...;
    return &result;    //Wrong! Don't do this!
}

the variable result ceases to exist when the function returns to its caller, and the returned pointer will be dangling. When the caller uses that pointer, your program exhibits undefined behavior, and pink elephants may appear.


Also note that space on the call stack is typically rather limited. You can ask malloc() for a gigabyte of memory, but if you try to allocate the same amount as an automatic array, your program will most likely segfault. That is the second reason d'etre for malloc(): To provide a means to allocate large memory objects.

-1

The classic way of handling a 2D array in 'C' where the dimensions might change is to declare it as a sufficiently sized one dimensional array and then have a routine / macro / calculation that calculates the element number of that 1D array given the specified row, column, element size, and number of columns in that array.

So, let's say you want to calculate the address offset in a table for 'specifiedRow' and 'specifiedCol' and the array elements are of 'tableElemSize' size and the table has 'tableCols' columns. That offset could be calculated as such:

addrOffset = specifiedRow * tableCols * tableElemSize + (specifiedCol * tableElemSize);

You could then add this to the address of the start of the table to get a pointer to the element desired.

This is assuming that you have an array of bytes, not integers or some other structure. If something larger than a byte, then the 'tableElemSize' is not going to be needed. It depends upon how you want to lay it out in memory.

I do not think that the way that you are doing it is something that is going to be portable across a lot of compilers and would suggest against it. If you need a two dimensional array where the dimensions can be dynamically changed, you might want to consider something like the MATRIX 'object' that I posted in a previous thread.

How I can merge two 2D arrays according to row in c++

Another solution would be dynamically allocated array of dynamically allocated arrays. This takes up a bit more memory than a 2D array that is allocated at compile time and the elements in the array are not contiguous (which might matter for some endeavors), but it will still give you the 'x[i][j]' type of notation that you would normally get with a 2D array defined at compile time. For example, the following code creates a 2D array of integers (error checking left out to make it more readable):

int  **x;
int  i, j;
int  count;
int  rows, cols;

rows = /* read a value from user or file */
cols = /* read a value from user of file */

x = calloc(sizeof(int *), rows);
for (i = 0; i < rows; i++)
    x[i] = calloc(sizeof(int), cols);

/* Initial the 2D array */
count = 0;
for (i = 0; i < rows; i++) {
    for (j = 0; j < cols; j++) {
        count++;
        x[i][j] = count;
    }
}

One thing that you need to remember here is that because we are using an array of arrays, we cannot always guarantee that each of the arrays is going to be in the next block of memory, especially if any garbage collection has been going on in the meantime (like might happen if your code was multithreaded). Even without that though, the memory is not going to be contiguous from one array to the next array (although the elements within each array will be). There is overhead associated with the memory allocation and that shows up if you look at the address of the 2D array and the 1D arrays that make up the rows. You can see this by printing out the address of the 2D array and each of the 1D arrays like this:

printf("Main Array:  0x%08X\n", x);
for (i = 0; i < rows; i++)
    printf("  0x08X [%04d], x[i], (int) x[i] - (int) x);

When I tested this with a 2D array with 4 columns, I found that each row took up 24 bytes even though it only needs 16 bytes for the 4 integers in the columns.

2
  • 1
    While you're might be correct, the answer does not address the question of "why this works" at all. May 25, 2020 at 4:23
  • It is one of those things that might work on some compilers, but not something that you can should expect to work on every compiler that you encounter. As such, it is something that I would avoid since during my career, my code was often running on a lot of different types of machines, many without even a C++ compiler available for it. May 25, 2020 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.