new and delete operators

This is a discussion on new and delete operators within the Linux Programming forums, part of the Platform Specific Boards category; int *p = new int[2]; delete [] p; The above sort of code is giving me major hassle! I'm using ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    4

    Exclamation new and delete operators

    int *p = new int[2];
    delete [] p;

    The above sort of code is giving me major hassle! I'm using a 2d array of pointers and can't seem to free up the memory space that it is occupying when I delete it.
    The pointer is set to NULL all right, but the data it used to point to is still there. I discovered this when I put another pointer pointing to the same data:

    int *q = p;

    After deleting p, q still points to the two integers in memory.
    This is really frustrating as it seems to have loads of implications. What if I had a linked list of 5000 records and decided to delete it? Would the memory ever be freed up?! Please help!

    I'm programming in Emacs,Linux

    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,855
    > I'm using a 2d array of pointers
    Well how did you use new to create the 2D array then?

    > but the data it used to point to is still there.
    Creating aliases for memory which has been deleted is a known cause of all sorts of problems.

    > After deleting p, q still points to the two integers in memory.
    Memory doesn't go anywhere when you delete it, only the official reference to that memory.
    But that doesn't mean you can read it, because at any moment, it could get re-used.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    4

    Talking

    Oh I see! Will having a second pointer keeping track of this value in memory after the first pointer (p) is deleted, prevent the data being overwritten in memory?

    I have a function which returns an array of 2pointers.
    Theis function is called three times, storing these reurned pointers in another pointer array.

    That's great! Thanks for the help

Popular pages Recent additions subscribe to a feed

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