Search code examples
c++arrayschardynamic-arrays

Heap corruption detected, while deleting a dynamic 2d char array


I have written a class with char** class field(which is dynamic 2d array) named visa(basically i want there to be countries which a person has visited) and countriesVisited(in fact size of the array). I intentionally didn't use strings. I've added a class method, which adds countries to the mentioned array, but when i try to delete the array elements i get HEAP CORRUPTION detected: after Normal block (#158):

void ForeignPassport::addCountry(const char* country) {   
        char** tmp = new char* [countriesVisited + 1];

    for (int i = 0; i < countriesVisited+1; i++) {
        tmp[i] = new char[strlen(country)];
    }


    for (int i = 0; i < countriesVisited; i++) {
        int f = 0;
        while (visa[i][f-1] != '\0') {
            tmp[i][f] = visa[i][f];
            f++;
        }
    }

    for (int i = 0; i <= strlen(country); i++) {
        if (i == strlen(country)) {
            tmp[countriesVisited][i] = '\0';
            break;
        }
        tmp[countriesVisited][i] = country[i];
    }
    countriesVisited++;
    
    for (int i = 0; i < countriesVisited-1; i++) {
        delete[]visa[i];
    }
    
    visa = tmp ;
    
}

Solution

  • tmp[i] = new char[strlen(country)];

    here you are allocating memory in amounts of strlen(country) but in this loop:

    for (int i = 0; i <= strlen(country); i++) {
            if (i == strlen(country)) {
                tmp[countriesVisited][i] = '\0';
                break;
            }
            tmp[countriesVisited][i] = country[i];
        }
    

    here you are accessing to the memory which is not allocated and this not allowed, so change the condition to i < strlen(country)