0

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;
}
3
  • 1
    Did you mean new int[cap*2] and new int[cap]? If so, you should have delete [] s; at the end, and do not delete p; at all. Commented May 4, 2022 at 20:03
  • 1
    delete p; two problems: p was previously deleted in doubleSize and you need delete[]. Second problem is repeated at delete s;. Commented May 4, 2022 at 20:05
  • 1
    Of course the real way to fix this problem is to use std::vector. Commented May 4, 2022 at 20:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.