Jump to content

  • Log In with Google      Sign In   
  • Create Account


#ActualShaquil

Posted 28 December 2012 - 07:18 PM

I'm sorry if this question has been asked before, but I'm struggling with figuring out how to google it right. I don't know how to pose the question without an example.

 

Say I have this code:

 

 

int main(){

   int * ptr = NULL;

   int input = 0;

   cin >> input;

   if(input > 5)
      ptr = new int;

  /*Apparently this doesn't work..*/
   if(ptr)
      delete ptr;

   return 0;
}

 

That's basically the way I've been checking if a pointer has been allocated dynamic memory or not, but I've just learned that my solution is wrong. So what might be one smart way to go about it? I just made the above code off the top of my head, so please don't criticize it for stuff that's off-topic from the question. Thanks a lot.


#1Shaquil

Posted 28 December 2012 - 07:16 PM

I'm sorry if this question has been asked before, but I'm struggling with figuring out how to google it right. I don't know how to pose the question without an example.

 

Say I have this code:

 

 

int main(){

   int * ptr = NULL;

   int input = 0;

   cin >> input;

   if(input > 5)
      ptr = new int;

  /*Is this the correct way to delete safely?*/
   if(ptr)
      delete ptr;

   return 0;
}

 

That's basically the way I've been checking if a pointer has been allocated dynamic memory or not, but I've just learned that my solution is wrong. So what might be one smart way to go about it? I just made the above code off the top of my head, so please don't criticize it for stuff that's off-topic from the question. Thanks a lot.


PARTNERS