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;
}
new int[cap*2]andnew int[cap]? If so, you should havedelete [] s;at the end, and do notdelete p;at all.delete p;two problems:pwas previously deleted indoubleSizeand you needdelete[]. Second problem is repeated atdelete s;.std::vector.