每天一道C\C++筆試題V—記憶體泄露

來源:互聯網
上載者:User

俗語云:出來混,遲早是要還的。

下面是一道初級記憶體泄露題,程式員小懶兒顯式的用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>leakstudent_number is 123name 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;}//hereStudent::~Student(){delete name;}int main(){Student *student = new Student(123,"linc");delete student;return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.