Is this a proper way of expanding array size dynamically?

Hi guys, I am wondering if this is the proper way to do the array expansion...

Does the line "ptr1 = ptr2" cause memory leak? Because initially both ptr1 and ptr2 point to different array of data, by executing that line, i wonder if the "delete[] ptr1" still can delete the array initially pointed by the ptr1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;

int main()
{
    int* ptr1;
    int* ptr2;

    ptr1 = new int[3];
    ptr1[0] = 1;
    ptr1[1] = 2;
    ptr1[2] = 3;


    ////here start the array expansion code;

    ptr2 = new int[4];
    ptr2 = ptr1;

    for (int i = 0; i < 3; i ++){cout <<ptr2[i] << endl;}

    delete[] ptr2;
    delete[] ptr1;

    return 0;
}
Yes it causes a memory leak. ptr2 = ptr1; is a simple assignment of pointers. If you want to copy the elements from one array to another you will have to use a loop and assign each element individually, or use std::memcpy or something like that.
ok, thanks
Topic archived. No new replies allowed.