Search code examples
c++arraysnew-operatordelete-operator

What is the exact behaviour of delete and delete[]?


Why is this code wrong? Am I missing something regarding the behaviour of delete and delete[]?

void remove_stopwords(char** strings, int* length) 
{
    char** strings_new = new char*[*length];
    int length_new = 0;

    for(int i=0; i<*length; i++) {
        if(is_common_keyword(strings[i]) == 0) {
            strings_new[length_new] = strings[i];
            length_new++;
        }
        else {
            delete strings[i];
            strings[i] = nullptr;
        }
    }
    delete[] strings;

    strings = new char*[length_new];
    for(int i=0; i<length_new; i++) {
        strings[i] = strings_new[i];
    }
    delete[] strings_new;
    *length = length_new;
}

Explanations: this code should take an array of C-style strings and remove some particular strings of them; the array of C-style strings was created using new[] and every C-style string was created using new. The result of the code is that no word is canceled, but the array is only sliced.


Solution

  • I don't see any problem in the use of new[] or delete[] in the code shown.

    No, wait.

    I see a lot¹ of problems, but your intent is clear and the code seems doing what you want it to do.

    The only logical problem I notice is that you're passing strings by value (it's a char** and reassigning it in the function will not affect the caller variable containing the pointer). Changing the signature to

    void remove_stopwords(char**& strings, int* length)
    

    so a reference is passed instead should fix it.

    (1) Using std::vector<const char *> would seem more logical, even better an std::vector<std::string> if possible, that would take care of all allocations and deallocations.