Menu

deleting dynamic arrays and instances

Kurgusov
2007-10-29
2012-09-26
  • Kurgusov

    Kurgusov - 2007-10-29

    I wonder if I can get someone to tell me wether the following code is proper.
    It compiles and runs fine but that doesnt mean jack.

    struct someStruct{
    int a ;
    int b ;
    int* c ;
    };

    // under main - p.s. all assigned numbers are irrelevant

    struct someStruct* ptr ;

    ptr = new someStruct[ 10 ] ;
    ptr -> c = new int [ 10 ] ;

    // do stuff with ptr.......

    delete [] ptr -> c ;
    delete [] ptr ;

    return 0 ;
    }

    Is that the correct way to delete them, or must I iforloop through each someStruct [ i ] and delete them like that ?
    Hope someone is willing to reply.

     
    • Anonymous

      Anonymous - 2007-10-29

      As written it is safe, but it is also probably nonsense. It depends what "do stuff with ptr..." does.

      The line,

      ptr -> c = new int [ 10 ] ;

      only allocates memory to the first struct in the ptr array. It is equivalent to:

      ptr[0].c = new int [ 10 ] ;

      If you later access ptr[1].c for example, the results will be undefined (and incorrect)

      In general you need one delete for each new. Here you have that, but as you say "that doesnt mean jack"!

      Note that a safer way to handle this is to use a constructor/destructor.

      struct someStruct
      {
      someStruct()
      {
      c = new int[10] ;
      }
      virtual ~someStruct()
      {
      delete [] c ;
      }
      int a ;
      int b ;
      int* c ;

      };

      Now the deletion of all memmory allocated to instances of someStruct are automatic, so you need just:

      ptr = new someStruct[ 10 ] ;
      //...
      delete [] ptr ;

      This is far safer and simpler. Note that in C++ a struct and a class differ only in default access and inheritance, so you don't need teh struct keyword when instantiating a struct object:

      someStruct* ptr ;

      is sufficient. To be honest however if you are going to have a constructor and destructor, you may as well properly define a class with private data members and access functions.

      Clifford

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.