俗语云:出来混,迟早是要还的。
下面是一道初级内存泄露题,程序员小懒儿显式的用new动态分配了内存,却忘记了用delete释放。
请找出问题的所在,代码如下:
#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; }用gcc编译运行:
D:\workspace\C++\memory_leak>gcc -o leak leak1.cpp -lstdc++ leak1.cpp: 在函数‘int main()’中: leak1.cpp:29:43: 警告:不建议使用从字符串常量到‘char*’的转换 [-Wwrite-strings] D:\workspace\C++\memory_leak>leak student_number is 123 name is linc虽然有编译器有警告,但是并不是提醒内存释放的问题。
其实上面的代码有两处没有释放内存,一个是Student的成员变量name没有在析构函数中释放掉;另一个是main函数中student用完要delete回收。
完整代码如下:
//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; } //here Student::~Student() { delete name; } int main() { Student *student = new Student(123,"linc"); delete student; return 0; }