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.
-- 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?