vendredi 5 mai 2023

Growing an integer array from the heap with C++ [duplicate]

I wrote the below C++ program to take user input, convert their string to an int, and then add it to a heap-based array. I am not using a vector to do this because I want to practice using pointers in C++.

When the current array arr grows past its maximum size, I add extra space to it with the add_space function and then insert the new number to the larger arr.

However, I am confused on how add_space does not lead to any crashes at runtime, like use-after-free errors. The bigger temp_arr array gets deleted from the heap, after arr started pointing to it. If we used arr again, wouldn't there be an issue since temp_arr got released and the original elements from the array got freed? I am confused on how the updated/expanded arr is able to be updated afterwards without any crashes.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

/* Grow the array */
void add_space(int *arr, unsigned int &size)
{
    int new_size = size * 2;
    int *temp_arr = new int[new_size];

    for (int i = 0; i < size; i++)
        temp_arr[i] = arr[i];
    
    size *= 2;
    arr = temp_arr;
    delete [] temp_arr;
    
    cout << "Done adding extra space\n";
}

void add_int(int *arr, int num, unsigned int &curr_size, int &i)
{
    arr[i++] = num;
    curr_size++;

    for (int j = 0; j < curr_size; j++)
        cout << arr[j] << " ";
    
    cout << endl;
}

int main()
{
    int *arr{nullptr};
    unsigned int size = 5;
    unsigned int curr_size = 0;
    int i = 0;
    string input;
    int input_num;

    arr = new int[size];
    
    do {
        cout << "Please enter a number to add to the list: ";
        cin >> input;
        cout << endl;

        if (input != "q" && input != "Q") {
            input_num = stoi(input);
            if (curr_size < size) {
                add_int(arr, input_num, curr_size, i);
            } else {
                add_space(arr, size);
                add_int(arr, input_num, curr_size, i);
            }
        }
    } while (input != "q" && input != "Q");

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire