Search code examples
c++arraysmemory-leaksdynamic-memory-allocation

Can this C++ code for growing an array possibly break?


I finally decided to learn C++ for good and I ran into the code below in a book that grows an array size. The function takes a pointer to an array with its original size and returns a new one with double the size.

int *doubleArraySize(int *p_array, int *p_size) {
    *p_size *= 2;

    int *p_new_array = new int[*p_size];
    for(int i = 0; i < *p_size; i++)
        p_new_array[i] = p_array[i];

    delete[] p_array;
    return p_new_array;
}

By the time we reach the for loop the value of *p_size has already been doubled. This means (at least to me) that when we access p_array[i] we end up in areas of the memory that do not belong to p_array. Is this an issue? Can this code ever crash?? If not, what am I missing?


Solution

  • That is not safe code. You copy from p_array beyond its limits (if it was the previous *p_size). While it probably will not crash, it's still undefined behavior.

    I have two suggestions:

    1. Use std::vector!
    2. If not, then at least use std::copy_n for the copying (with the correct size of course).