H.L.Alumnus
H.L.Alumnus

Reputation: 69

Heap corruption upon using delete[] on an array

This is my code:

int* mergeArrays(int* a, int m, int* b, int n)
{
    int *c;
    c = new int(m + n);
    int i, j;
    for (i = 0; i < m + n; i++)
        c[i] = 0;
    for (i = 0; i < m; i++)
        c[i] = a[i];
    cout << i;
    for (j = 0; j < n; j++)
    {
        c[i] = b[j];
        i++;
    }
    for (i = 0; i < m + n - 1; i++)
        for (j = i + 1; j < m + n; j++)
            if (c[i] > c[j])
                swap(c[i], c[j]);
    return c;
}

Error appear when I use delete[]a in main() Anyone know how to solve this?

Upvotes: 0

Views: 59

Answers (1)

Yu Hao
Yu Hao

Reputation: 122493

c = new int(m + n);

This allocates a pointer to one int, and initialize its value to m + n.

What you want is:

c = new int[m + n];

Upvotes: 1

Related Questions