c++ - Error free(): invalid next size (fast): 0x08912058 -


as part of exercise, modifying class represents different way of creating arrays:

template<class t> class array  { public:  array(int size, t defaultvalue) : _size(size)      {     _arr = new t[_size] ;     _def = defaultvalue;     }   array(const array& other) : _size(other._size)      {     _arr = new t[other._size] ;     // copy elements     (int i=0 ; i<_size ; i++)          {             _arr[i] = other._arr[i] ;             }     }  ~array()      {         delete[] _arr ;     }   array& operator=(const array& other)      {     if (&other==this) return *this ;         if (_size != other._size)          {             resize(other._size) ;             }         (int i=0 ; i<_size ; i++)          {             _arr[i] = other._arr[i] ;             }         return *this ;     }  t& operator[](int index)      {                    if (index>_size)         {         int prevsize = _size;         resize(index);         (int = prevsize+1; i<=index; i++)             {             _arr[i] = _def;             }         }         return _arr[index] ;     }  const t& operator[](int index) const      {         if (index>_size)         {         int prevsize = _size;         resize(index);         (int = prevsize+1; i<=index; i++)             {             _arr[i] = _def;             }         }         return _arr[index] ;     }  int size() const { return _size;}  t defval() const { return _def;}  void resize(int newsize)      {         // allocate new array         t* newarr = new t[newsize] ;     // copy elements     (int i=0 ; i<_size ; i++)          {             newarr[i] = _arr[i] ;             }     // delete old array , install new 1         delete[] _arr ;         _size = newsize ;         _arr = newarr ;     }   private: int _size ; t* _arr ; t _def; } ; 

now works fine arrays of ints, gives me

*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x08912058 ***

when do, instance:

const char* 1 = new char[3]; 1 = "abc"; array<const char*> b(2, one); 

this should create array of length 2, , time acces element index > 2, should return string "abc". when access such element, array returns it's supposed to, aforementioned error. error followed backtrace.

your resize function resizes size give (i.e. index), set array (and including) index. that's invalid index - array goes 0 index-1.

i'm talking lines:

resize(index); (int = prevsize+1; i<=index; i++) 

so need call resize index+1 fix problem.

also:

const char* 1 = new char[3]; 1 = "abc"; 

this leaks memory (you allocate new buffer , set one "abc" different pointer).


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -