So I have this question, I'm currently learning how to get dynamic memory to allocate variables in the heap (on C++), so I just create a struct and put some items on it, then in the deleteList(estructura *) function i delete all variables, the problem is that I'm getting huge amounts of memory allocated, hence leaks.
struct estructura
{
char *algo;
double *algo2;
estructura *next;
};
estructura* lastEstructura(estructura *head)
{
estructura *current = head;
while (current -> next)
{
current = current -> next;
}
return current;
}
void crearLista(estructura *head)
{
for (int i = 0; i < 8200; i++)
{
estructura *current = new estructura;
current -> algo = new char[100];
current -> algo2 = new double;
current -> next = nullptr;
estructura *temp = lastEstructura(head);
temp -> next = current;
}
}
void deleteList(estructura *head)
{
estructura *current = head;
while (current) {
estructura *temp = current;
current = current -> next;
delete [] temp -> algo;
delete temp -> algo2;
temp -> next = nullptr;
delete temp;
}
}
int main(int argc, const char * argv[])
{
int i = 0;
cout << "enter: ";
cin >> i;
do {
estructura *head = new estructura;
head -> algo = new char[100];
head -> algo2 = new double;
head -> next = nullptr;
crearLista(head);
deleteList(head);
cout << "enter: ";
cin >> i;
} while (i == 1);
return 0;
}
I really want to understand this, why do I get this leaks, so please somebody help me, I already tried searching and didn't find something that could help me. (I'm relatively new to C++)
Part of your problem is that you're allocating the members of an allocated object. Your code will be simpler if you just had:
struct estructura
{
char algo[100];
double algo2;
estructura *next;
};
That way, new estructura
gives you the full structure that you need and then delete current
is the only thing you need to do. Also if you add a new member to estructura
, everything just works without you having to worry about adding another new
/ delete
pair.
You delete structure fields but you do forget to delete the structure instance. And also, you create a list very inefficiently. You do it in O(n^2) when it can be done in O(n).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.