0

We were writing a code in our university (learning about Object Oriented Program). We wrote this class and the issue is that, as per my understanding and our teacher the program should crash in the following condition, but in my case it doesn't.

The thing is this line is the culprit

DynamicArray d, f;
f = d;

according to him(rest of the code is attached), since when main ends, deconstructor deletes f and then goes for d, but since pointer was pointing to same mem location in both cases, now it should give error when it tries to delete it, since there is nothing there....but my compiler runs the code perfectly. I am using gcc compiler. Denconstructor at the end of class, rest is to fill dynamic array.

#include <iostream>
#include <ctime>

class DynamicArray{

private:
    int *arr;
    int size, cap; //cap is the physical size, size is number of elements

public:
    DynamicArray(){
        arr = nullptr;
        size = cap = 0;
    }
    DynamicArray(int i){
        cap = i;
        size = 0;
        arr = new int[cap];
    }
    void pushback(int j){

        if(cap == 0){
            arr = new int[cap];
            arr[0] = j;
            size++;
            cap++;
        }
        else if(size < cap){
            arr[size] = j;
            size++;
        }
        else if(size == cap){
            int *arr2 = new int[cap * 2];
            int i;
            cap *= 2;

            for(i = 0; i < size; i++){
                arr2[i] = arr[i];
            }
            arr2[i++] = j;

            delete[] arr;
            arr = arr2;
        }
    }
    void print(){
        for(int i = 0; i < size; i++)
            std::cout << arr[i] << " ";
    }
    ~DynamicArray(){
        if(arr != nullptr)
            delete[] arr;
    }
};

int main(){

    DynamicArray d, f;

    srand(time(nullptr));
    int n = rand() % 5;

    for(int i = 0; i < n; i++){
        d.pushback(rand() % 10);
    }

    f = d;

    f.print();
    std::cout << std::endl;
    d.print();

    return 0;
}

1 Answers1

4

Your code causes so-called "undefined behaviour". Basically, that means anything can happen, including that nothing happens or that whatever happens isn't easily observable. For a more precise definition of "undefined behaviour", you'd have to check e.g. the C++ standard, but there are also many discussions concerning this term here.

Try running your code using e.g. valgrind, it will tell you that your code is broken.

Ulrich Eckhardt
  • 15,392
  • 1
  • 25
  • 49