pexea12
pexea12

Reputation: 1209

Memory Management with delete

I have a little program:

#include <iostream>

using namespace std;

void inputArray(int*& p, int& n);
void print(int *p, int n);

int main() {
    int size = 0;
    int *arr;
    inputArray(arr, size);
}

void inputArray(int*& p, int& n) {
    int *q = new int[n]; int m = n;
    for (int i = 0; i < n; ++i) q[i] = p[i];
    cout << endl << "How many numbers to insert? "; cin >> n;
    delete p; 
    p = new int[n + m];
    for (int i = 0; i < m; ++i) p[i] = q[i];
    for (int i = 0; i < n; ++i) cin >> p[i + m];
    n += m;
}

The purpose of this program is to insert an array of integer. However, when I try to run the program with Code::Blocks on Ubuntu, it often says:

free(): invalid pointer: 0xb7646000 ***

after I input n.

However, when I remove delete p; , everything works well. However, I still want to know the problem. Can anyone tell what the problem is?

Upvotes: 1

Views: 55

Answers (2)

Mekap
Mekap

Reputation: 2085

 delete p; 

You never allocated p, so when you try to free p, it can't. It's like trying to access someone else's bank account, you may have the name, but you ain't allowed to free his money.

And - just for the rant- , try using more verbose variable names, it never hurts. Especially if you drunk-review your code in a year.

Upvotes: 4

Cory Kramer
Cory Kramer

Reputation: 117866

You are assigning elements from the array p

for (int i = 0; i < n; ++i) q[i] = p[i];

But p was never allocated or assigned any values

int *arr;
inputArray(arr, size);   // Here "arr" is "p" within the function

This constitutes undefined behavior and will behave as such.

Upvotes: 3

Related Questions