vendredi 31 mai 2019

Using Smart Pointers

Am working on a legacy C++ app which has below function,

char* CreateNewString (const char* node)
{
   int len = (int) strlen(node) + 1;
   char * ptr = new char [len];
   strcpy_s(ptr, len, node);
   return ptr;
}

This function is called from many classes in the app and here's an example usage case.

char * nodeID = obj.CreateNewString(process->GetNodeID());

The app calls a different process and get a node ID as char pointer and then it's passed to CreateNewString function to dynamically allocate memory for a new string.

Nowhere in the app after the above call, it's deleting the memory. From what i observe, there's a definite memory corruption here.

I think there're few ways of resolving this issue. But i want to explore using the smart pointers in C++11 first before trying anything else.

What I Tried:

So i came up with below function.

  char* CreateNewString (const char* node) 
  {
       int len = (int) strlen(node) + 1;
       shared_ptr<char> ptr (new char [len](), [](char* p) {delete [] p;});
       strcpy_s(ptr.get(), len, node);
       return ptr.get();
    }

The goal is to keep function signature same, i.e., it returns a char pointer, so that i don't have to make changes at all calling places.

The above is not working as ptr is released as it's declared inside the scope of this function.

My goal is:

  1. Use C++ 11 smart pointers to achieve this with minimum code changes to the existing application.

An alternative way am aware of, dynamically initialize array in calling places itself and then delete it before end of that scope. But I want to explore new C++ features before going back to traditional C++ way.

Aucun commentaire:

Enregistrer un commentaire