One C \ C ++ exam every day V-Memory leakage

Source: Internet
Author: User

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;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.