L
L
Lockdown62021-11-18 04:51:48
C++ / C#
Lockdown6, 2021-11-18 04:51:48

Will memory be freed if we use the clear() method on a vector that has been filled with structures?

name = new char[20];
std::cin >> name;
data.push_back(Student{(short) data.size(),name});
data.clear();

I created a struct:
struct Student
{
    int id;

    char *name;
};

For name, I allocate memory dynamically, and also the structures are stored in vector.

The question is, what happens if I use the clear() method to clear all the structures in the vector?
All dynamically allocated memory for name will be released or all objects in vector will be deleted, but there will be a memory leak?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Reshetnikov, 2021-11-18
@Lockdown6

name will not be released, there will be a memory leak.
If you need to free memory, then it is better to do Student as a class and, accordingly, create name in the constructor and release it in the destructor

R
res2001, 2021-11-18
@res2001

In C++, a struct is basically the same as a class.
Implement a destructor in the structure, in which the memory under name will be released. When deleting elements in a vector (clear), a destructor will be called for each existing element.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question