Hi folks ,i dont understand why free my resources stuck.
This is my code:
Class Person
{
char* name;
public:
Person(const char* name):name(NULL)
{
This->name=strdup(name);
}
~Person(){delete[] name;}
};
Class School
{
Person* persons;
int numOfPersons;
public:
School(int numOfPersons):numOfPersons(numOfPersons)
{
persons=new Person[numOfPersons];
}
void setPerson(int index,Person& p)
{
persons[index]=p;
}
~School(){delete[] persons;}
};
void main()
{
Person p("John");
School s(2);
S.setPerson(0,p);
}
The problem is after the program has finnished it stuck in freeing memory.
I think it because it is trying to free p twice ,if this is the case what should i do?
I think it because it is trying to free p twice ,if this is the case what should i do?
First use code tags when posting code!
Second the problem is probably being caused because you're trying to delete[] something that wasn't allocated with new[]. But this is only a guess because there are errors in the code that will not allow the code to actually compile when using a modern standard compliant compiler.
The strdup() function returns a pointer to a new string which is a duplicate of the string s. Memory for the new string is obtained with malloc(3), and can be freed with free(3).
Person's destructor calls delete [] on something allocated with malloc.
That happens on p's destruction at the end of main().
That happens on s[0]'s destruction at the end of main() too,
because s[0].name == p.name due to copy assignment with setPerson.
The destructor of s[1] attempts to deallocate too. What does the s[1].name point to?
Please consider using std::string (for strings) and std::vector (for dynamic arrays) if you don't absolutely need to do manual dynamic memory management.