mardi 30 janvier 2018

C++11 Error - What does this error mean when I try to dynamically increase the size of an array?

I am using this algorithm for dynamically increasing the size of an array:

void resize(int* oldArray, int* capacity) {
*capacity = *capacity * 2;
int* new_array = new int[*capacity];
for (int i = 0; i < *capacity/2; i++) {
    new_array[i] = oldArray[i];
}
delete[] oldArray;
oldArray = new_array;

}

However, when I build and run this algorithm I get the following error:

r3(21751,0x7fff8d76e340) malloc: * error for object 0x7f8ca5c026c0: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug Abort trap: 6

Also, this is the main function I am using:

int main(int argc, char* argv[]) {
if (argc != 2) {
    return -1;
}

std::ifstream inFile(argv[1]);
int capacity = 10;
int* num_array = new int[capacity];
int num_elements = 0;

if (inFile.is_open()) {
    std::string line;
    while (!inFile.eof()) {
        getline(inFile,line);
        if (num_elements == capacity) {
            resize(num_array,&capacity);
        }
        int num = stoi(line);
        num_array[num_elements++] = num;
    }

    for (int i = 0; i < num_elements; i++) {
        std::cout<<num_array[i]<<std::endl;
    }
}

}

Can anyone please tell me why this is happening? Thank you!

Aucun commentaire:

Enregistrer un commentaire