First of all, it is incorrect to use memcpy
to copy non-POD types. Just use a for loop, or std::copy
.
Second, you are doing more work than necessary (and you have a memory leak).
void Stack<Type>::resize(int capacity) {
if(capacity >= MAX_SIZE)
capacity = MAX_SIZE;
Type* copy = new Type[capacity];
for (int i = 0; i < N; i++) {
copy[i] = s[i];
}
Up to this point, you're okay. You've allocated a new array, and assigned over the elements from the old array. I'm assuming N
is the number of valid elements.
s = new Type[capacity];
Assuming that s
previously pointed to an allocated array, this is a memory leak. First, you need to delete the previous data.
delete [] s;
Then, you don't need to allocate another array. Use the one you just allocated.
s = copy;
All together, the function now looks like this:
template <class Type>
void Stack<Type>::resize(int capacity) {
if(capacity >= MAX_SIZE)
capacity = MAX_SIZE;
Type* copy = new Type[capacity];
for (int i = 0; i < N; i++) {
copy[i] = s[i];
}
delete [] s;
s = copy;
size = capacity;
}
If there are still problems, some other part of your code is broken.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…