Verbal Kint wrote:
Hi.
I would like to know something about the code below. I know, that's not
a nice programming style, because before using the new-Operator a
second time, I should use delete first. But its working fine anyway. So
what is the worst that could happen to my program if I leave it like
that?
CODE:
int main()
{
int i,*val;
val = new int[5];
for (i=0;i<5;i++)
val[i]=i;
val = new int[10];
for (i=0;i<10;i++)
val[i]=i;
delete[] val;
return 0;
}
The first thing that might happen is that you develop a nasty habit. In
the case above, there is no reason to be allocating on the heap in the
first place. Whats disturbing with that code, is that you lose the
original pointer with which you reserved the original allocation.
Think of some coder thats comes along, scans the code quickly, assumes
that the delete[] statement above recovers the entire allocation and
proceeds to reuse your code/class with the assumption that no leaks
have occurred.
Using new/delete also makes code more difficult to write (and
maintain).
#include <iostream>
#include <ostream>
#include <vector>
void load(std::vector< int >& r_v)
{
for( size_t i = 0; i < r_v.size(); ++i)
{
r_v[i] = i;
std::cout << "v[" << i << "] ";
std::cout << r_v[i] << std::endl;
}
}
int main()
{
std::vector< int v(5); // a dynamic array of 5 elements
load( v );
v.clear();
v.resize(10);
load( v );
}