Delete pointer

This is a discussion on Delete pointer within the C++ Programming forums, part of the General Programming Boards category; Hi, I've just read this topic - "Lesson 6: An introduction to pointers" The delete operator frees up the memory ...

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    2

    Delete pointer

    Hi,
    I've just read this topic - "Lesson 6: An introduction to pointers"

    The delete operator frees up the memory allocated through new. To do so, the syntax is as in the example.

    delete ptr;
    Could you tell me more about that and give me any example?
    How can I use it?

    Code:
    int x = 10;
    int *ptr;
    ptr = &x;
    cout << ptr << " " << *ptr << endl;
    
    delete ptr;    //Is it ok?
    
    cout << ptr << " " << *ptr << endl; //What should be as a result? I've got error: memory violation.

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,915
    int* x = new int;
    cout << ptr << " " << *ptr << endl;
    delete x;

    You can only delete what you new.
    You cannot use *ptr after you've deleted it.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    682
    Quote Originally Posted by Chris_thf View Post
    Hi,

    Code:
    int x = 10;
    int *ptr;
    ptr = &x;
    cout << ptr << " " << *ptr << endl;
    
    delete ptr;    //Is it ok?
    
    cout << ptr << " " << *ptr << endl; //What should be as a result? I've got error: memory violation.
    You cannot delete pointer to x, because you didn't allocate memory of x on your own.

  4. #4
    Registered User
    Join Date
    Sep 2010
    Posts
    2
    OK, I understand.
    Thank you very much.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing Argument from incompatible pointer type
    By AmritxD in forum C Programming
    Replies: 3
    Last Post: 08-15-2010, 04:23 PM
  2. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 04:47 PM
  3. Inventory tracking of dynamically allocated items
    By Mario F. in forum C++ Programming
    Replies: 11
    Last Post: 07-23-2006, 06:39 PM
  4. delete pointer inside ?
    By black in forum C++ Programming
    Replies: 7
    Last Post: 05-28-2004, 01:19 PM
  5. API "Clean Up" Functions & delete Pointers :: Winsock
    By kuphryn in forum Windows Programming
    Replies: 2
    Last Post: 05-10-2002, 07:53 PM

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