0

Basically i have this code:

===========================

A.h

class A {

    int state = -1;

public:
    void print();

    void set(int i);
};

===========================

A.CPP

void A::print() {
    cout<<state<<endl;
}

void A::set(int i) {
    state = i;
}

===========================

MAIN

int main() {

    A a[2];

    a[0].set(1);
    a[1].set(2);

    a[0].print();
    a[1].print();
    a[2].print();
    a[3].print();

    return 0;
}

And this is what is shown in the console:

1
2
1542598400
1919717043

And if i change main in this way:

int main() {

    A a[1]; // <---- CHANGE

    a[0].set(1);
    a[1].set(2);

    a[0].print();
    a[1].print();
    a[2].print();
    a[3].print();

    return 0;
}

This is shown:

*** stack smashing detected ***: <unknown> terminated
1
2
1054043105
-2010162576

I don't understand what's happening

Axel
  • 1
  • 1
  • 1
    With your second example, only the access to a[0] is legal, as the array has only one element (of index 0). So with a[1], you just got lucky, like somebody crossing a mine field and escaping unscathed. As for elements 2 and 3, they were not initialized at all by your code, so you just get what happened to be on the stack before. In modern C++, it is recommended to use std::vector instead of traditional arrays. With vectors, you get a choice of unchecked access (with []), and runtime-checked access with the `a.at(indexValue)` syntax. See about `std::vector` on cppreference.com for details. – jpmarinier Mar 11 '20 at 23:38
  • The array is just a pointer to memory, so if you don't do any of the `a[0].set(...)` functions, you'll just have the pointer and it will point to some random stuff that's already there in memory. When you set it, with `.set()` or perhaps `.clear()`, that's when you know the information in the array is usable. The random numbers you're getting are just that, random data left in memory that your program is looking at through the pointer. – Maxime Franchot Mar 11 '20 at 23:40

0 Answers0