Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the debugger show only one element from my array pointer?

First off: I know that new is the C++ way of doing this. I am simply showing that there is more than one way to reproduce this error, and both are incredibly frustrating.

I have two forms of this source file. I'm trying to debug yet another programming assignment, but I'm not asking for help on that. Basically, I'm trying to re-implement set as a class with fields for size and a pointer to an int array. Here's the code using new:

testnew.cpp

int main()
{
    int size = 1;
    int *elements = new int[size];
    elements[0] = 0;
    size++;
    int * temp = new int[size];
    for (int i = 0; i < (size - 1); i++)
    {
        temp[i] = elements[i];
    }
    delete[] elements;
    temp[size] = size;
    elements = temp;
    elements[1] = 1;
    delete[] elements;
}

and again, using the less-preferable alloc functions:

testalloc.cpp

int main()
{
    int size = 1;
    int * elements = (int *) malloc(sizeof(int) * size);
    elements[0] = 0;
    size++;
    elements =(int *) realloc(elements,size * sizeof(int));
    elements[1] = 1;
    free(elements);
}

In both cases, my goal is to create an array, and then append to it. However, in both cases, after building and running it in Visual Studio 2010, the array is not grown at all, and only has 1 "slot" for my items to go into. In VS's debugger, I have watches on the elements array pointer; attached is a screenshot. It is the same for both versions of the code.

My watches at the end of the program

-- the breakpoint is at the delete[]/free() call.

Seriously, what am I doing wrong? This has to be a logic error, and I've combed through a quarter dozen examples of both malloc/realloc and new, and read and re-read my textbook, and I can't see what's wrong!

I feel like I should have a line that splits the allocated memory into an array, but doesn't the new int[] call do that?

like image 876
Tasuret Avatar asked Dec 13 '25 01:12

Tasuret


1 Answers

Besides any other issues with the code, you must either do what JoeG mentions and have multiple watches, or set a watch like this:

elements,5

will result in:

enter image description here

I don't know if there is an updated list for VS2010, but this still works: Symbols for Watch Variables
And: View array in Visual Studio debugger?

like image 86
crashmstr Avatar answered Dec 14 '25 18:12

crashmstr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!