Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array memory allocation in C depends on naming convention?

I've encountered a weird phenomenon in C which I need someone to explain. I have the code below with 2 single element arrays as global variables. I am printing the memory address of the first and second element of each array (note that the array was defined to have only 1 element):

#include <stdio.h>

int a1[1];
int a2[1];

int main(void) {

    a1[0] = 100;
    a2[0] = 200;

    printf("%d\n", &a1[0]);
    printf("%d\n", &a1[1]);
    printf("%d\n", &a2[0]);
    printf("%d\n", &a2[1]);
}

This gives the following output. Note that C allocated a contiguous memory block for array a2 right after a1 (hence address of a1[1] and a2[0] are same):

4223424
4223428
4223428
4223432

However, something miraculous occurs when I change the names of the arrays. I added "zzz" as prefix to both the arrays as below.

#include <stdio.h>

int zzza1[1];
int zzza2[1];

int main(void) {

    zzza1[0] = 100;
    zzza2[0] = 200;

    printf("%d\n", &zzza1[0]);
    printf("%d\n", &zzza1[1]);
    printf("%d\n", &zzza2[0]);
    printf("%d\n", &zzza2[1]);
}

After running this code you can see from the following output that the memory was allocated for the array zzza2 first and thereafter for zzza1 (&a2[1] = &a1[0]):

4223428
4223432
4223424
4223428

I have tested the above code with multiple array sizes (2,4,8) in various different machines at different times and got the same output so it is not a coincidence. This does not happen when I define the variables within main() as local variables.

It seems C is allocating memory based on the name we provide to the arrays. Firstly, why does C allocate contiguous blocks to different global arrays everytime? Secondly, when I add the prefix, why is the order of memory allocation changing?

Hope this doesn't baffle everyone as it has me... Thanks for your help in advance!

like image 249
Kunal Kapoor Avatar asked Sep 02 '15 03:09

Kunal Kapoor


1 Answers

Firstly, why does C allocate contiguous blocks to different global arrays everytime?

Because one contiguous block is more effective and easier to implement. If application allocates global variables at different memory blocks it has at least one of next drawbacks:

  1. Wasted memory between blocks.
  2. Complicated memory allocation at start.

So toolchain tries to allocate all global variables at one contiguous memory block.

like image 184
Dmitrii Bulashevich Avatar answered Oct 03 '22 11:10

Dmitrii Bulashevich