Memory Allocation with Adjacent Arrays

I was fiddling around with two arrays in C, trying to get one of them to invade the memory space of the other. As a beginner I understand the compiler automatically allocates memory space for the arrays in my example, but how are these memory addresses chosen? For example, in the below code (compiled by my browser on c++.com website) the addresses for numbers[] and stealth[] respectively are:

0x75fbb51092c0

0x75fbb51092b0

which I calculated were 16 bytes apart. Is this some safety measure so that that one array doesn't enter another's space?

// more pointers
#include <iostream>
using namespace std;

int main ()
{
  int numbers[5];
  int stealth[1];

for (int i=0;i<6;i++){
    if (i==0){
        stealth[i]=9;
    }
    else {
        numbers[i]=i;  
    }
  }
  int * a;
//  b=numbers;
  a=numbers;


  cout << "value at 0 index for numbers: "<< *a << endl;
  cout << "address: " << a << endl;

  a=stealth;

  cout << "value at 0 index for stealth: "<< *a << endl;
  cout << "address: " << a << endl;


  return 0;
}

++++ EDIT ++++ Thanks for your input. After some further testing I set pointer to an array to an integer's location. Then I iterated through the array and printed out the memory address at every index value. Yet, the index at the beginning of the array has a different address than the one had set to the integer earlier. Any ideas why? I pasted new code and output below:

// more pointers
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  int numbers[5]={1,2,3,4,5};
  int alien=6;

  int * a;
  int * b;
  b=numbers;
  a=&alien;
  b=a;
  cout << "address of start of array numbers: " << b << endl;
  cout << "address of alien: " << a << endl;

  for (int i=0;i<5;i++){
    cout << &numbers[i] << endl;
    cout << numbers[i] << endl;    
  }
  return 0;
}

OUTPUT

address of start of array numbers: 0x79ab503a591c
address of alien: 0x79ab503a591c
0x79ab503a5920
1
0x79ab503a5924
2
0x79ab503a5928
3
0x79ab503a592c
4
0x79ab503a5930
5

1 answer

  • answered 2018-01-14 05:23 SoronelHaetir

    Any variables (other than unions) that you allocate on the stack will have their own storage, that is a guarantee of the language. The address is chosen partly by the compiler but mostly by the operating system. The higher part of the address (amount varies by system but usually at least 0x1000) will be chosen by the OS whole lower parts will depend on the compiler.

    The only way you would get an array to invade the space occupied by a different variable would be if you were to mess around with pointers and many of those operations would result in undefined behavior.