Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a little trouble understanding memory allocation in C

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?

like image 753
cantcode4mylife Avatar asked Mar 02 '23 10:03

cantcode4mylife


1 Answers

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.

like image 140
John Bollinger Avatar answered Mar 05 '23 16:03

John Bollinger