Home > Mobile >  How is it determined which memory block to use in c/c ?
How is it determined which memory block to use in c/c ?

Time:05-18

This is the code I wrote:

#include <iostream>
using namespace std;

int main() {
    int x[3] = {30,31,32}, y[3] = {40,41,42}, z[3] = {50,51,52};

    for (int i=0; i < 3; i  ) {
        cout << *(x i) << endl;
        cout << *(x-(3-i)) << endl;
        cout << *(x-(6-i)) << endl;
    }
    cout << endl;
    for (int i=0; i < 3; i  ) { 
        cout << (long int)&x[i] << endl; // address of x
    }
    cout << endl;
    for (int i=0; i < 3; i  ) {
        cout << (long int)&y[i] << endl; // address of y
    }
    cout << endl;
    for (int i=0; i < 3; i  ) {
        cout << (long int)&z[i] << endl; // address of z
    }
}

Here is the output:

30
40
50
31
41
51
32
42
52

140701886846268
140701886846272
140701886846276

140701886846256
140701886846260
140701886846264

140701886846244
140701886846248
140701886846252

Here you can see the array which was declared at last takes the foremost memory address and second last takes memory address after the last one and so on.

CodePudding user response:

Here you can see the array which was declared at last takes the foremost memory address and second last takes memory address after the last one and so on.

No, this is not what is happening. The program has undefined behavior because you're going out of bounds of the array for the expressions *(x-(3-i)) and *(x-(6-i)) for different values of i.

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program. In your case this means that you have to make sure that you don't go out of bounds of the array.


1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

  • Related