1

I have sample code below. The ServantI.cpp:login method, it construct a New UserContext. Before context is returned, it is assigned to new Session's sessionContext field, which is UserContext*;

//idl: 
 struct UserContext{
    string name;
    string ipaddress;
    string ssoToken;
  };
   UserContext login(in string name, in string cipher) raises (AuthenticationException);
   void logout(in string name);


// servantI.cpp
  ::project::UserContext * servantI::login (
  const char * name,
  const char * cipher)
{
  project::UserContext* context = new UserConytext(); ...
  boost::shared_ptr<Session> session(new Session(name, context));
  map.addSession(name, session);
  return context;
}

void servantI::logout (const char * name)
{
   map.remove(name);
}

//Session.h: 
class Session
{
std::string _username;
UserContext* _sessionContext;
public:
Session(string name, UserContext* context){ _sessionContext = context; ..}
virtual ~Session(void){
    cout<<"Call descrutction "<<endl;
}
}

My question is whether there is memory leakage in Session Class since there is place to free _sessionContext pointer. It is also report run-time unhandle exception if I change

        UserContext* _sessionContext; 

to

        UserContext_var _sessionContext;

in class Session

Martin Ba
  • 37,187
  • 33
  • 183
  • 337
shijie xu
  • 1,975
  • 21
  • 52

1 Answers1

3

The implementation of servantI::login is correct wrt. the return value.

  • There is no memory leak, the ORB will clean up the pointer you new'ed up here.
  • If you use a (local) UserContext_var you need to use ._retn()

And wrt. the map and the storing of the userContext:

You cannot store the new'ed up UserContext* context like you do in the code above. It will be destroyed by the ORB when you return from the servantI::login function. If you need to store it, store a copy of the UserContext -- it a simple value structure after all.

Session should then look:

class Session {
  std::string _username;
  UserContext _sessionContext;
public:
  Session(string name, UserContext const& context)
  : _username(name)
  , _sessionContext(context)
  { }
  ...
Martin Ba
  • 37,187
  • 33
  • 183
  • 337
  • Thanks. So in the Class Session, with "UserContext* _sessionContext;", i should not explicit free _sessionContext. All new instances of IDL generated type would be deallocated by ORB finally and we should not clean them – shijie xu Feb 03 '14 at 23:46
  • I think Martin is correct, but still there seems to be something wrong here. It is true that the ORB will free the pointer that you return from the function. But you have made a copy of this pointer and put it in the map. If you try to use this pointer after the ORB has freed the memory bad things will likely happen. – Brian Neal Feb 06 '14 at 03:08