Search code examples
c++arrayspointersdelete-operator

How do I stop my resize function from causing _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse)?


I've been tasked with implementing a stack using arrays However, when I run the program it says _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse). The debugger directed me to the delete statement in the resize function, but I'm unsure how to fix the problem.

Note: I'm trying to do so without using vectors.

   void resize(){
       Type* temp = new Type[asz + 2];  // store old values
       for (int i = 0; i < asz; ++i){ temp[i] = arr[i]; }
       delete[asz] arr;             // delete old array
       arr = temp;                  // keep new larger arr
       delete[] temp;
       asz =+2; // array size
       }

Solution

  • Here's a couple of changes that may fix your problem. You don't initialise sz, your final for-loop was copying according to the new increased size, yet tempwas only the old size. You also don't appear to set the new sz anywhere. Could be any or all of these that cause a memory overwrite invalidating the debug blocks and causing the assertion you have seen.

      void resize(Type& arg){
           Type* temp = new Type[arg.sz];   // store old values
           for (int i = 0; i < arg.sz; ++i){ temp[i] = arg[i]; }
           int oldSz = arg.sz, newSz=arg.sz + 2;
           delete[] arg;                // delete old array
           arg = new Type[newSz];          // create new larger arr
           arg.sz = newSz;
           for (int i = 0; i < oldSz; ++i){ arg[i] = temp[i]; } //copy back
           delete[] temp;
           }