As the saying goes: you have to pay back it sooner or later.
The following is a preliminary Memory Leak question. The programmer's little lazy explicitly uses new to dynamically allocate the memory, but forgets to use delete to release the memory.
Find out the problem. The Code is as follows:
#include <iostream>#include <cstring>using namespace std;class Student{int student_number;char* name;public:Student(int,char*);};Student::Student(int number,char* _name){student_number = number;name = new char[strlen(_name)+1];strcpy(name,_name);cout<<"student_number is "<<student_number<<endl;cout<<"name is "<<name<<endl;}int main(){Student *student = new Student(123,"linc");return 0;}
Compile and run with gcc:
D: \ workspace \ C ++ \ memory_leak> gcc-o leak leak1.cpp-lstdc ++ leak1.cpp: In the 'int main () 'function: leak1.cpp: 29: 43: Warning: it is not recommended to convert from String constant to 'Char * '[-Wwrite-strings] D: \ workspace \ C ++ \ memory_leak> leakstudent_number is 123 name is linc
Although there is a warning from the compiler, it does not remind the memory to be released.
In fact, the above Code has not released the memory. One is that the name of the Student member variable is not released in the Destructor; the other is that the student in the main function needs to be deleted after use.
The complete code is as follows:
//linc//2013.3.7//C++ memory leak ,case 1#include <iostream>#include <cstring>using namespace std;class Student{int student_number;char* name;public:Student(int,char*);virtual ~Student();};Student::Student(int number,char* _name){student_number = number;name = new char[strlen(_name)+1];strcpy(name,_name);cout<<"student_number is "<<student_number<<endl;cout<<"name is "<<name<<endl;}//hereStudent::~Student(){delete name;}int main(){Student *student = new Student(123,"linc");delete student;return 0;}