delete pointers, but not the pointed object

This is a discussion on delete pointers, but not the pointed object within the C++ Programming forums, part of the General Programming Boards category; I have a linked list, and in one of the functions I create a new object that points to one ...

  1. #1
    Unregistered
    Guest

    Question delete pointers, but not the pointed object

    I have a linked list, and in one of the functions I create a new object that points to one of the objects one the list.

    Node* newPointer=new Node;
    newPointer=myList->getHead()->getNext();

    Is it possible to delete THE POINTER, and the pointer only Ė not the pointed object. If I write
    delete newPointer;
    then the object itself is deleted. I donít want to do that!

    If it donít delete the newPointer will this lead to memory leakage?

    Hope anyone can help me

    -xagiber-

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786
    Cant you create another pointer and reassign the object to that?

  3. #3
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    you seem a little mixed up concerning the scope of your variables....

    Node* newPointer=new Node;

    letsexamine this in more detail....

    new Node

    this part of the expression returns a pointer to a dynamically allocated chunk of memory. This is the chunk of memory that will need to be freed with delete.

    Node* newpointer=

    this part of the expression declares a local pointer variable on the stack. As it is local this pointer will automatically be destroyed when it leaves scope. Do not lose this pointer before you have had a chance to delete the newed memory or you will have a memory leak.

    hope that helps.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 25
    Last Post: 04-29-2008, 06:32 AM
  2. delete pointers
    By rnx40401 in forum C++ Programming
    Replies: 15
    Last Post: 10-29-2007, 04:30 PM
  3. Inventory tracking of dynamically allocated items
    By Mario F. in forum C++ Programming
    Replies: 11
    Last Post: 07-23-2006, 05:39 PM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. Creating an array of object pointers
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 10-08-2001, 10:01 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21