When I run this I get a segmentation fault but I'm not sure where it is. This is in c++. Any help appreciated, thanks in advance
template<typename T>
void My_vec<T>::insert_at_rank(int r, const T& elem){
int init_size = size;
if(r < 0){
cerr << "Out of range"<<endl;
exit(EXIT_FAILURE);
}
else if (r <= size) {
++size;
}
else
size = r+1;
if (size > capacity) {
T* new_ptr = new T[capacity*2];
for (int i = 0; i < capacity; i++) {
new_ptr[i] = ptr[i];
}
capacity = 2 * capacity;
delete[] ptr;
ptr = new_ptr;
free(new_ptr);
}
for(int i = size-1; i > r; i--){
ptr[i] = ptr[i-1];
}
for (int i = init_size; i < r; i++) {
ptr[i] = '0';
}
ptr[r] = elem;
}
答案 0 :(得分:1)
T* new_ptr = new T[capacity*2]; // allocates new array
//...
delete[] ptr; // deletes previous array that 'ptr' pointed to
ptr = new_ptr; // repoints 'ptr' to the newly allocated array
free(new_ptr); // ???
问题#1:new_ptr
已分配new []
。要取消分配,您必须使用delete []
而不是 free
。
问题#2:ptr = new_ptr;
设置ptr
指向与T[]
相同的new_ptr
数组。解除分配new-ptr
后ptr
指向未分配的空间。然而,后续代码试图在ptr[i]
中取消引用它。那个UB(undefined behavior),并且预先设置了段错误,实际上是所有场景中最幸运的