c++ - I have a segmentation fault and cannot seem to find it -


when run segmentation fault i'm not sure is. in c++. appreciated, 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];             (int = 0; < capacity; i++) {               new_ptr[i] = ptr[i];             }         capacity = 2 * capacity;         delete[] ptr;         ptr = new_ptr;         free(new_ptr);         }          for(int = size-1; > r; i--){             ptr[i] = ptr[i-1];         }         (int = init_size; < r; i++) {             ptr[i] = '0';         }         ptr[r] = elem;       } 

    t* new_ptr = new t[capacity*2];  // allocates new array     //...     delete[] ptr;   // deletes previous array 'ptr' pointed     ptr = new_ptr;  // repoints 'ptr' newly allocated array     free(new_ptr);  // ??? 

problem #1: new_ptr allocated new []. deallocate it, must use delete [] not free.

problem #2: ptr = new_ptr; sets ptr point same t[] array new_ptr. after new-ptr deallocated ptr left pointing unallocated space. yet, subsequent code attempts dereference in ptr[i]. that's ub (undefined behavior), , having program segfault upfront luckiest of scenarios


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -