I am creating a program and while dynamically allocating an integer array, i try to delete the array from the heap in the same function I create it in. But valgrind is saying there are 20 bytes definitely lost/in use at exit.
Here is the function:
int whoStarts(Parent* parents, int num){
int* connects = new int[num];
for(int i = 0; i < num; i++){
connects[i] = 0;
}
for(int i = 0; i < num;i++){
for(int j = 0; j < num; j++){
if(parents[i].name == parents[j].connectedName){
connects[i]++;
}
}
}
for (int i = 0;i < num;i++){
if(connects[i] == 0){
return i;
}
}
delete [] connects;
return 0;
}`
I am not sure why the memory is not being freed, I have another dynamically allocated array that i create in a function, return a pointer back to main for a struct array, but I delete that one in the main function. Valgrind points to this one giving this error:
==820297== 20 bytes in 1 blocks are definitely lost in loss record 1 of 1
==820297== at 0x4C38B6F: operator new[](unsigned long) (vg_replace_malloc.c:640)
==820297== by 0x402254: whoStarts(Parent*, int) (phone_tree.cpp:114)
==820297== by 0x401C39: main (phone_tree.cpp:38)
on line 38 i assign an int the value returned by the whoStarts function.
can anyone give me any advice on how to free this memory?
>Solution :
Something like this maybe:
int whoStarts(Parent* parents, int num){
int* connects = new int[num];
int status = 0;
for(int i = 0; i < num; i++){
connects[i] = 0;
}
for(int i = 0; i < num;i++){
for(int j = 0; j < num; j++){
if(parents[i].name == parents[j].connectedName){
connects[i]++;
}
}
}
for (int i = 0;i < num;i++){
if(connects[i] == 0){
status = i;
break;
}
}
delete [] connects;
return status;
}