aurora
aurora

Reputation: 67

Valgrind errors from dynamically allocated arrays in C++

The program is aimed to take a dynamically allocated array and return a new dynamically allocated array with double the size that copies the values in the first one and leaves the rest uninitialized. However, it's getting valgrind errors in main(). Any suggestions on how to fix the memory issues?

#include <iostream>

using std::cout;
using std::endl;

int * doubleSize(int * p, int & cap) {
    //create dynamically allocated double size array
    int *doubleSize = new int(cap * 2);
    
    //store old array values into new array
    for (int i = 0; i < cap; i++) {
        doubleSize[i] = p[i];
    }

    cap = cap * 2; 

    delete[] p; //deallocate old memory

    return doubleSize;
}

int main() {
    int cap = 3;
    int *p = new int(cap);
    //initialize an array
    for (int i = 0; i < cap; i++) {
        p[i] = i;
    }
    
    int *s = doubleSize(p, cap);

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

    //deallocate memory
    delete p;
    delete s;
}

Upvotes: 0

Views: 158

Answers (1)

user4581301
user4581301

Reputation: 33982

Several problems in the code:

int *p = new int(cap);

and

int *doubleSize = new int(cap * 2);

both allocate a single int with the value cap or cap * 2

Since arrays of int are expected by the rest of the code, these need to be corrected to

int *p = new int[cap];

and

int *doubleSize = new int[cap * 2];

Then

delete p;
delete s;

must be changed to

delete[] p;
delete[] s;

in order to correctly delete arrays.

But!

delete[] p;

already happened back in doubleSize when the array was replaced. It could be removed, but the code would be cleaner with

p = doubleSize(p, cap);

and the variable s being removed instead.

Upvotes: 2

Related Questions