Dynamic Memory Management Within A Class

I consider myself an o.k. programmer but I've only taken intro courses (self-taught mostly), but this took me and the PAL(Programming Assistance Lab) at my college by surprise.

This following code crashes after execution and I have traced it back to the addValue method, I know the way I am adding values is useless but it should work regardless (I have cut the code down to eliminate possibilities). NO error messages, NO warnings.

I'm assuming I am missing something about the way variables are stored in classes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;
class constTest
{
    private:
        int *xArray;
        int x;
    public:

        constTest(int);
        ~constTest();
        void addValue(int);
};
constTest::constTest(int iSize)
{
    int *xArray = new int[iSize];
    x = iSize;

}
constTest::~constTest()
{
    delete[] xArray;
}
void constTest::addValue(int value)
{

    xArray[0] = value;

    return;
}

int main()
{
    constTest Array(5);
    Array.addValue(5);


}
You never initialize (allocate memory for) the xArray member, so line 27 is writing to a bad pointer.

The mistake is here:

1
2
3
4
5
constTest::constTest(int iSize)
{
    int *xArray = new int[iSize];  // <- not what you want
    x = iSize;
}


This is a mistake because you are creating ANOTHER pointer with the same name as your member. Now you have two pointers named 'xArray', one is local to the ctor, and one is a member.

the local one gets initialized, then goes out of scope and dies. The member remains unchanged (uninitialized).

The solution:

1
2
3
4
5
constTest::constTest(int iSize)
{
    xArray = new int[iSize];  // <- do not create another variable
    x = iSize;
}
Oh my god... I totally missed that. Completely and totally, was a psychological problem more than anything; since class var's are initialized in the class body i totally forgot that I obviously wouldn't need to re-initialize. Thank you so much, you have the greatest eyes ever.
You are redeclaring your array in the constructor.
Topic archived. No new replies allowed.