Question

I have an array of pointers that point to arrays of ints. I have made a hard coded array of ints (check 'array' below) and I want to insert it into the array of pointers (check 'bar' below), as far as I can tell, it is still an array of pointers that point to arrays of ints.

It compiles fine; no warnings. It runs fine; and closes fine; Until at least, I introduce the currently commented out delete statement in the destructor.

I imagine my compiler would make a better destructor at this point, but I'm interested as to what I'm doing wrong. The terminal window just throws out a gigantic memory map; and googling and searching SO didn't help much.

class foo {
    public:
    int **bar;
    int aSize;

    //CONSTRUCTOR
    foo(int aSize) {
        this->aSize = aSize;
        bar = new int*[aSize];
        for (int i=0;i<aSize;i++) {
            bar[i] = new int[aSize + i];
            for (int j=0;j<(aSize + i);j++) {
                bar[i][j] = 0;
            }
        }
        }
    void myfunc(int *pointer) {
        bar[0] = pointer;
    }
    ~foo() {
        for (int i=0;i<aSize;i++) {
            //delete[] bar[i];
        }
        delete[] bar;
    }
};
int main() {
    foo *obj = new foo(5);

    int array[] = {1,2,3,4};

    obj->myfunc(array);

    delete obj;
    return 0;
};

I know I've probably done something tragic; I just don't know what it is yet. There is a reason why I am not using STL or other templates, it is simply because I'm interested in learning this. Maximum criticism appreciated.

Was it helpful?

Solution

The myfunc function takes in a pointer, and then sets bar[0] to that memory address. In your example code, you pass it the address of array, which is an automatic (stack) variable. The destructor then attempts to delete[] bar[0], which points to a stack variable. This is completely undefined behavior, and the reason your program is crashing. You can't delete[] a stack array. You can only delete[] an array which was allocated using new[].

Also, the myfunc function is always going to leak memory, because bar[0] points to a heap-allocated array. When you set bar to a different memory address without first delete[]ing the previous address, you are leaking memory.

OTHER TIPS

The problem is calling myfunc. In that function, you are replacing a pointer (bar[0]) that your class thinks it owns. Your obj destructor will then consequently try to run delete[] on your array[] in main, which probably causes your crash and leaves your original bar[0] dangling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top