开发者

Memory release issue in C++

开发者 https://www.devze.com 2023-01-28 07:41 出处:网络
We have code similar to the one below. We are trying to achieve RAII using a class calledMemRelease class. Now, FXOMemRelease is being used the way shown in sample.cc.

We have code similar to the one below. We are trying to achieve RAII using a class called MemRelease class. Now, FXOMemRelease is being used the way shown in sample.cc.

Is this OK to use the obeject of FXOMemRelase like that ? Most of the time I see that the destructor for MemRelease only gets called after MakeString() is completed. That is fine.

Will it be the case always ? We got a memory issue and the truss output last pointed to the print statement in the MemRelease class.

MemRelease.cpp

template<typename T>
MemRelease<T>::MemRelease(T* store, unsigned char array_yesno, short release_yesno)
        : ptr(store), array(array_yesno), release(release_yesno)
{
}


template<typename T>
T* MemRelease<T>::getStore()
{
        return (ptr);
}

template<typename T>
MemRelease<T>::~MemRelease()
{
        if (!release) return;
         if ( (array == 'Y') || (array == 'y') )
        {
                cout << "deleting array in MemRelease pid = " << getpid() << endl;
                delete [] ptr;
                ptr = NULL;
        }
        else
        {
                cout << "deleting memory in MemRelease pid = " << getpid() <<  endl;
                delete ptr;
                ptr = NULL;
        }
}

Sample.cc:

char* MakeString(char* str)
{
   cout << "Entered MakeString\n";
   char* newstr = new char[strlen(str) + 1];
   strcpy(newstr, str);
   return str;
}
int main()
{
   char *str = new char[10];
   strcpy(str, "jagan");
   char* newstr = Ma开发者_如何学运维keString(MemRelease<char>(str).getStore());

   getchar();
   delete newstr;
}


instead of using delete, use delete[] because you are allocating memory using new[].

Since you are using C++, why don't you use std::string or boost::scoped_ptr boost::scoped_array and their friends?


Most of the time I see that the destructor for MemRelease only gets called after MakeString() is completed. That is fine. Will it be the case always ?

Yes, always. The temporary object stays valid until the assignment to newstr completes.

As afriza points out, we can't verify which destruction code is running because you haven't included the default values for the constructor's array_yesno and release_yesno. BTW, there's a type called bool which should be used for yes/no values.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号