c++ - Allocation of memory for return value in function and memory leaks -


i have function:

char const* getdata() const  {       char* result = new char[32];       sprintf(result, "my super string");        return result; } 

adn show string on screen this:

std::cout << getdata() << std::endl; 

or have class:

class myclass() {     char m_data[32] public:      myclass(const char* data) { strcpy(m_data, data) } ; } 

and create instance of object:

myclass obj = new myclass(getdata()); 

i allocate char* result = new char[32]; , never delete this. how should deal memory leak ? how should free memory ?

c++ best feature comes deterministic object destruction (this point taken bjarne).

it allows raii idiom. make sure read it, should clear should use objects manage resources. essentially, when write program, know when each object's destructor called. use knowledge @ advantage delegate resource management object destructor free resources (and make sure object destructed when want free resource ^^)

as pointed in comments, if need string of characters, stl gives object manage underlying dynamic char array lifetime :

 std::string 

how rewrite first method

taking advantage of std::string facility :

std::string getdata() const  {      return std::string("my super string"); } 

but not need function here, create std::string object directly wherever need in code.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -