Search code examples
c++memory-managementnew-operatordynamic-memory-allocationdelete-operator

Deleting a temporal Array in C++


I was working with dynamic memory from a book that I got. As far as I understand every time that we create a new variable we need to delete it, and set the pointer to null, so we don't have dangling pointers .

I created a program that stores values from users in a dynamic Array of [5], and whenever the user adds more I "expand" the array. When expanding, I use a temporary new array that gives me a tough time when I try to delete it. Why does this happen?

size_t arraySize(5), index(0);

int inputvalue(0);
int *ptemporal(nullptr);

int *pvalues = new int[arraySize];

    for (;;){

        cout << "Enter value or 0 to end: ";
        cin >> inputvalue;  //enter value

        // exit loop if 0
        if (!inputvalue)  //if 0 break
            break;

        pvalues[index++] = inputvalue; //store values on pivalores

        if (index == arraySize){ //if limit reached create space

            cout << "Limit reached. Creating space...";

            arraySize += 5; //5 new memory blocks

            ptemporal = new int[arraySize]; //temporal value holder.

            for (size_t i = 0; i < arraySize - 5; i++)  //xfer values to temporal
                ptemporal[i] = pvalues[i];

                delete[] pvalues;       // delete values to  
                pvalues = ptemporal;  // assigning the same addres to pvalues.

                **delete[]  ptemporal; //causes a problem if I use the delete. if i comment the program works just fine.**

                ptemporal = nullptr;
        }


    }
return 0;
}

**The two asterics are just to show were the problem occurs.


Solution

  • Your issue is that you are deleting ptemporal right after you copy the pointer to pvalues:

    pvalues = ptemporal; // assigning the same addres to pvalues.
    
    delete[]  ptemporal; //causes a problem if I use the delete. if i commentt the program works just fine.**
    

    In other words, you delete the memory you just created! So the next time you expand the vector, you try to delete it again, resulting in a double free error. This sort of error is where a debugger helps, so you can watch the variable values as your program executes.

    // start
    ptemporal = nullptr;
    pvalues   = /* location A */;
    
    
    // first expansion
    ptemporal = /* location B */;
    // copy values from location A to B
    delete[]    pvales;    /* location A */
    pvalues   = ptemporal; /* location B! */
    delete[]    ptemporal; /* location B */
    ptemporal = nullptr;
    
    
    // second expansion
    ptemporal = /* location C */;
    // copy values from location B to C, should segfault
    
    // then you delete pvalues (aka location B) again!
    // this results in a double free error
    delete[]    pvales;    /* location B */
    

    To fix this, simply remove the line delete[] ptemporal;