user2813556
user2813556

Reputation: 3

Dynamic Memory C++

I have a trouble while I delete memory allocated with the next code:

int main(){
    char **cities;

    cities = new char*[MAX_CITIES];
    for(int i = 0; i < MAX_CITIES; i += 1){
        cities[i] = new char[MAX_CITY_LENGTH];
        cities[i] = "CITY"; //Its only a test value
    }
    cout << "Memory allocated successfully" << endl;

    for(int i = 0; i < MAX_CITIES; i += 1){
        cout << cities[i] << endl;
    }

    for(int i = 0; i < MAX_CITIES; i += 1){
        delete[] cities[i];
    }
    delete[] cities;
    cout << "Memory freed successfully" << endl;
    return EXIT_SUCCESS;
}

I hope you can help me. Thanks.

Upvotes: 0

Views: 79

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490068

The problem is right here:

cities[i] = "CITY"; //Its only a test value

This does not copy CITY into the memory you must allocated. Instead, it overwrites the pointer to the memory you just allocated with a pointer to the string literal "CITY".

When you try to delete that, problems arise because it's not memory that was allocated with new. Since you overwrote the pointer to the memory you allocated, it just gets leaked.

To make it work, replace cities[i] = "CITY"; with strcpy(cities[i], "CITY"); so you copy the characters into the memory you allocated.

Having said that, use std::vector<std::string> if you have any choice in the matter at all.

Upvotes: 3

Related Questions