This is a simple question and I'm kind of a beginner, but I would just like to confirm this.
Say I have a class object int * data, which is pointing to an array of 5 ints. Say I have a function that would replace data with 5 arguments, as illustrated below.
void replaceData(int a, int b, int c, int d, int e){
int * temp = new int[5];
temp[0] = a;
temp[1] = b;
temp[2] = c;
temp[3] = d;
temp[4] = e;
data = temp;
}
I am concerned that this would cause a memory leak, because if data already had 5 ints in there, they would still be floating around. I am tempted to change it in the following way to avoid this:
void replaceData(int a, int b, int c, int d, int e){
int * temp = new int[5];
temp[0] = a;
temp[1] = b;
temp[2] = c;
temp[3] = d;
temp[4] = e;
delete data; //would this prevent a memory leak?
data = temp;
temp = 0;
}
Thank you very much for your input!
Almost.
The delete
operator is for pointers to single objects. You need to do delete[] data
for this to work. Zeroing the temp pointer at the end doesn't make a difference.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments