I'm playing with the idea of having the user enter ints until a -1 is entered. Every int that is entered is stored in an dynamic array.
My thought process on this was to keep deleting and recreating new memory of +1 size larger, and then have another block of the same size to keep the data, and then finally copy them back and forth to one another.
I'm sure there is an error in my logic or implementation ( or both! ) but any help would be appreciated!
My code seems to work for 4 iterations, and then all hell breaks loose. I'll post the error at the end since it's really long.
// Program Name : ints.cpp
// Compiler : g++
// Written By : Steven Riedel <steven.riedel@gmail.com>
// Playing With : Moving data from one chuck of dynamic memory and
// then back again, increasing in size.
#include <iostream>
usingnamespace std;
int main( void ) {
int input;
// the new number being entered.
int size = 0;
// my counter.
int* ptr = newint;
int* temp = newint;
// pointers to memory I'm going to be working with.
do {
cout << "Enter a number : ";
cin >> input;
*( ptr + size ) = input;
// put the data into the memory
temp = newint[ size ];
// askes for some more memory so I can copy ptr into it.
for ( int i = 0; i <= size; i++ ) {
*( temp + i ) = *( ptr + i );
// copies what is in ptr into temp, element by element
}
delete ptr;
size++;
ptr = newint[ size ];
// asks for more memory so I can enter a new number into it.
for ( int i = 0; i <= size; i++ ) {
*( ptr + i ) = *( temp + i );
// puts the number from temp back into ptr
}
delete temp;
} while ( input != -1 );
delete ptr;
return 0;
}
For a start, this code leaks the int sized block stored in temp.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int size = 0;
// my counter.
int* ptr = newint;
int* temp = newint;
// pointers to memory I'm going to be working with.
do {
cout << "Enter a number : ";
cin >> input;
*( ptr + size ) = input;
// put the data into the memory
temp = newint[ size ];
Then the next few lines overwrite the buffer allocated to temp.
1 2 3 4 5 6
// askes for some more memory so I can copy ptr into it.
for ( int i = 0; i <= size; i++ ) {
*( temp + i ) = *( ptr + i );
// copies what is in ptr into temp, element by element
}
Plus as imi said, you've use new int and new int[] on temp, and you don't know which delete to call.