Hello I am having a problem with this function. Everything works fine until it reaches the delete []dynamicArray line. Can someone please tell me why it would crash at this part?

string* addEntry(string *dynamicArray, int &size, string newEntry)
{
    string* hold;
    hold = new string[size + 1];        
    for (int i = 0; i < size; i++)
    {
        *hold = *dynamicArray;            //copy the names over into new array
        hold++;
        dynamicArray++;
    }
    *hold = newEntry;                     //add the new name
    size++;
    delete []dynamicArray;                //delete the old array
    cout << "I don't crash" << endl; 

    return hold;                          //return the pointer to the new array
}

Is the array that you pass in to this function as dynamicArray allocated using new[]? If not this would cause a crash. If you could, it might help if you post a fragment of the code that calls this function.

This kind of thing is one reason why you should use smart pointers and not raw pointers, or std::vector for arrays. Basically, you should almost never have to type delete in your code.

Yes sir here is the function I use to allocate my dynamicArray:

string* Allocate()
{
    string* hold;
    hold = new string[5];

    return hold;
}

and here is the way I call it in my main function:

array = Allocate();

Ah, actually we didn't need to see any other code! The issue is evident in the original piece you posted. You need to ask yourself: what is dynamicArray pointing to when you call delete[] on it? Is it what delete[] expects it to be pointing to?

Ok so i did a for loop to take the pointer back to the begining, but it still crashes.

nvm got it

string* addEntry(string *dynamicArray, int &size, string newEntry)
{
    string* hold, *temp, *holdReturn;
    hold = new string[size + 1];
    holdReturn = new string[size + 1];
    holdReturn = hold;
    temp = new string[size];
    temp = dynamicArray;         
    for (int i = 0; i < size; i++)
    {
        *hold = *temp;                    //copy the names over into new array
        hold++;
        temp++;
    }
    *hold = newEntry;                     //add the new name
    size++;
    delete [] dynamicArray;               //delete the old array

    return holdReturn;                    //return the pointer to the new array
}

Be careful! Now you have three new's and only one delete. What is the new on line 7 doing?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.