problem with deleting pointers??

This is a discussion on problem with deleting pointers?? within the C++ Programming forums, part of the General Programming Boards category; Hi I just get a simple problem: Code: #include <iostream.h> void main() { int i = 2; int* ptest = ...

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    173

    problem with deleting pointers??

    Hi

    I just get a simple problem:

    Code:
    #include <iostream.h>
    
    void main()
    {
      
    
      int i = 2;
      int* ptest = &i;
      delete ptest;
    
    }
    the app crashed when I ran it, why?

    Thanks
    Don't laugh at me,I am just a SuperNewbie.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    You are deleting memory you haven't allocated with new.

    int main(), not void main().
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,555
    > delete ptest;

    If you have
    int *ptest = new int;
    Then you need at some point, exactly one
    delete ptest;

    If you have
    int *ptest = new int[some_number];
    Then you need at some point, exactly one
    delete [] ptest;

    Trying to delete anything else is a really bad idea.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with pointers in strcat
    By Elros in forum C Programming
    Replies: 2
    Last Post: 08-15-2007, 10:54 PM
  2. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  3. very weird problem (pointers I think)
    By hannibar in forum C Programming
    Replies: 2
    Last Post: 10-11-2005, 06:45 AM
  4. Pointers problem
    By blackswan in forum C Programming
    Replies: 8
    Last Post: 10-07-2005, 12:23 PM
  5. Problem deleting a node from a linked list
    By Dag_ in forum C++ Programming
    Replies: 1
    Last Post: 03-17-2005, 08:53 AM

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