I have a segmentation fault and cannot seem to find it

时间:2016-02-03 03:18:04

标签: c++

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;  
    }

1 个答案:

答案 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-ptrptr指向未分配的空间。然而,后续代码试图在ptr[i]中取消引用它。那个UB(undefined behavior),并且预先设置了段错误,实际上是所有场景中最幸运的