Thread: Please explain structure behaviour

  1. #1
    Registered User
    Join Date
    Jan 2007

    Please explain structure behaviour

    Hi ,

    Can anybody explain me the strange behaviour of structure pointer......

    I have the following code....

    struct ABC
      int age;
      long salary;
      char* name;
    class file
       ABC* read(char*);
       void write(ABC*);
     ABC* file::read(char* namePass)
      ABC *a =new ABC;
     else{ return NULL;}
     return a;
    // The above function is called as follow in another CPP file......
    ABC *abc;
    file *m_file;
    ABC *abc =new ABC;
    delete abc;
    cout<<abc->age; // IT's returning valid value. 23
    I want to know that when I have deleted the pointer abc.....then why should it giving the correct value.......???????

    Please conside the case when it read function returns NULL......


  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Deleting a pointer neither sets your pointer to NULL, nor trashes the memory which was being pointed to.

    But then again, your code is broken to begin with, since you ignore the return result and leak the memory you allocate in your read() function.

    > then why should it giving the correct value
    No reason at all.
    Perhaps using a "debug" build which trashes memory as soon as you delete it would help you.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem referencing structure elements by pointer
    By trillianjedi in forum C Programming
    Replies: 19
    Last Post: 06-13-2008, 05:46 PM
  2. Reference to a Structure
    By boschow in forum C Programming
    Replies: 3
    Last Post: 03-28-2008, 02:37 PM
  3. Passing Structure Pointers to Functions
    By samus250 in forum C Programming
    Replies: 15
    Last Post: 03-20-2008, 03:13 PM
  4. Replies: 13
    Last Post: 12-14-2007, 03:34 PM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM