Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. new&delete, malloc&free

new&delete, malloc&free

Scheduled Pinned Locked Moved C / C++ / MFC
performancequestion
8 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Offline
    R Offline
    raner
    wrote on last edited by
    #1

    Hi I've always read that with every "new" there shld be a "delete" and likewise with "malloc" and "free", otherwise it'll lead to memory leak.However when the application is terminated, will this resources be freed? Once, i've created an object with "new" in a loop and was unable to delete the object outside the loop.Anyone knows why? thks!

    J A 2 Replies Last reply
    0
    • R raner

      Hi I've always read that with every "new" there shld be a "delete" and likewise with "malloc" and "free", otherwise it'll lead to memory leak.However when the application is terminated, will this resources be freed? Once, i've created an object with "new" in a loop and was unable to delete the object outside the loop.Anyone knows why? thks!

      J Offline
      J Offline
      jhwurmbach
      wrote on last edited by
      #2

      raner wrote: However when the application is terminated, will this resources be freed? Yes. In debug mode, the IDE shows nasty comments about the leaks, but thats it. So, if your app starts, runs a second, leaking a few KB of memory and terminates, no harm is done. But if you imagine MS-Word would leak one byte per keystroke, you see how this would lead to trouble. Basically, dont leak at all! It is not that hard to acomplish if you are careful: Drop char* in favor of std::string or CString, drop dynamic C-arrays in vavor of std::vector etc. Those pointers that you need are initialised at creation, checked against NULL before use and set to NULL after the delete. raner wrote: Once, i've created an object with "new" in a loop and was unable to delete the object outside the loop.Anyone knows why? You threw away the pointer to this object, eg. overwriting it in the next loop iteration? Remember:
      My opinions may have changed, but not the fact that I am right.

      R 1 Reply Last reply
      0
      • J jhwurmbach

        raner wrote: However when the application is terminated, will this resources be freed? Yes. In debug mode, the IDE shows nasty comments about the leaks, but thats it. So, if your app starts, runs a second, leaking a few KB of memory and terminates, no harm is done. But if you imagine MS-Word would leak one byte per keystroke, you see how this would lead to trouble. Basically, dont leak at all! It is not that hard to acomplish if you are careful: Drop char* in favor of std::string or CString, drop dynamic C-arrays in vavor of std::vector etc. Those pointers that you need are initialised at creation, checked against NULL before use and set to NULL after the delete. raner wrote: Once, i've created an object with "new" in a loop and was unable to delete the object outside the loop.Anyone knows why? You threw away the pointer to this object, eg. overwriting it in the next loop iteration? Remember:
        My opinions may have changed, but not the fact that I am right.

        R Offline
        R Offline
        raner
        wrote on last edited by
        #3

        jhwurmbach wrote: Drop char* in favor of std::string or CString, drop dynamic C-arrays in vavor of std::vector etc. By std::vector, are u referring to STL?..Sorry i'm not very familiar with VC yet. For the use of "new" in the loop, yes, i reassigned the pointer to consecutive elements in an array at each iteration.Do i not need to delete the pointer then? thks alot!

        J 1 Reply Last reply
        0
        • R raner

          jhwurmbach wrote: Drop char* in favor of std::string or CString, drop dynamic C-arrays in vavor of std::vector etc. By std::vector, are u referring to STL?..Sorry i'm not very familiar with VC yet. For the use of "new" in the loop, yes, i reassigned the pointer to consecutive elements in an array at each iteration.Do i not need to delete the pointer then? thks alot!

          J Offline
          J Offline
          jhwurmbach
          wrote on last edited by
          #4

          Yes std:: is the namespace where the STL resides. Read the tutorials here at CP, and you will understand how it works, and soon be a follower of the
          GREAT STL *manic laugh* ;) As to the loop, you said you could not delete memory you newed in a loop. If you have overwritten the pointer to this memory (being your only access) in the next iteration, you can not delete it: A delete on your pointer deletes only the last newed memory.


          My opinions may have changed, but not the fact that I am right.

          R 1 Reply Last reply
          0
          • R raner

            Hi I've always read that with every "new" there shld be a "delete" and likewise with "malloc" and "free", otherwise it'll lead to memory leak.However when the application is terminated, will this resources be freed? Once, i've created an object with "new" in a loop and was unable to delete the object outside the loop.Anyone knows why? thks!

            A Offline
            A Offline
            AlexO
            wrote on last edited by
            #5

            The best way to understand the difference is to analyze what new/delete is actually doing. new(global new operator): 1. Call operator new of the data type to allocate n bytes of memory. Default implementation just calls ::malloc(n) 2. Call constructor of the given data type for the new object delete (global delete operator): 1. Call destructor of the given data type for the object being deleted 2. Call operator delete of the data type to free the memory. The default implementation just calls ::free(p). Example main() { A* pA = new A();//1. call ::new //2. call A::operator new(...) //3. call A::A() delete pA; ;//1. call ::delete //2. call A::~A //3. call A::operator delete(...) } The array and build in types are slightly different, but we can ignore the difference for now. Now about loop allocation int* pi = 0; for(int i = 0; i < 100;++i) { pi = new int;//we allocate new int //if we do not call delete before next iteration //we are going to loose memory when pi is //reassign to new value } I hope it helps AlexO P.S. I did not cover constructor/destructor invokation order, I assume you already know about that

            1 Reply Last reply
            0
            • J jhwurmbach

              Yes std:: is the namespace where the STL resides. Read the tutorials here at CP, and you will understand how it works, and soon be a follower of the
              GREAT STL *manic laugh* ;) As to the loop, you said you could not delete memory you newed in a loop. If you have overwritten the pointer to this memory (being your only access) in the next iteration, you can not delete it: A delete on your pointer deletes only the last newed memory.


              My opinions may have changed, but not the fact that I am right.

              R Offline
              R Offline
              raner
              wrote on last edited by
              #6

              ok..i see the point now. But can i confirm that the following statements should be fine? int* pi = 0; for(int i = 0; i < 100;++i) { pi = new int; //I'll store pointer pi of each iterationin some kind of array, so it can be retrieved later } delete pi;

              J 1 Reply Last reply
              0
              • R raner

                ok..i see the point now. But can i confirm that the following statements should be fine? int* pi = 0; for(int i = 0; i < 100;++i) { pi = new int; //I'll store pointer pi of each iterationin some kind of array, so it can be retrieved later } delete pi;

                J Offline
                J Offline
                jhwurmbach
                wrote on last edited by
                #7

                raner wrote: But can i confirm that the following statements should be fine? [..example deleted..] No! You have 100 'new int' instructions (in the loop), but only one delete (after the loop). You are leaking 99 ints. This one works:

                #include < iostream >
                #define num 100
                int main(int argc, char* argv[])
                {
                typedef int* intPtr;
                //allocate memory for an array of int*, size of array is num
                intPtr* pI = new intPtr[num];

                //allocate the numbers
                for(int i = 0; i < num; ++i)
                {
                    pI\[i\] = new int;
                    \*pI\[i\] = i\*i;
                }
                
                //use the numbers
                for( i = 0; i < num; ++i)
                    std::cout << "i: " << i << "  i quadrat: " << \*pI\[i\] << std::endl;
                
                //delete the content of the arry of pointers
                //that is, delete the numbers
                for(i = 0; i < num; ++i)
                {
                    delete pI\[i\];
                }
                //delete the array of pointers to numbers
                delete\[\] pI; 	
                
                return 0;
                

                }


                My opinions may have changed, but not the fact that I am right.

                R 1 Reply Last reply
                0
                • J jhwurmbach

                  raner wrote: But can i confirm that the following statements should be fine? [..example deleted..] No! You have 100 'new int' instructions (in the loop), but only one delete (after the loop). You are leaking 99 ints. This one works:

                  #include < iostream >
                  #define num 100
                  int main(int argc, char* argv[])
                  {
                  typedef int* intPtr;
                  //allocate memory for an array of int*, size of array is num
                  intPtr* pI = new intPtr[num];

                  //allocate the numbers
                  for(int i = 0; i < num; ++i)
                  {
                      pI\[i\] = new int;
                      \*pI\[i\] = i\*i;
                  }
                  
                  //use the numbers
                  for( i = 0; i < num; ++i)
                      std::cout << "i: " << i << "  i quadrat: " << \*pI\[i\] << std::endl;
                  
                  //delete the content of the arry of pointers
                  //that is, delete the numbers
                  for(i = 0; i < num; ++i)
                  {
                      delete pI\[i\];
                  }
                  //delete the array of pointers to numbers
                  delete\[\] pI; 	
                  
                  return 0;
                  

                  }


                  My opinions may have changed, but not the fact that I am right.

                  R Offline
                  R Offline
                  raner
                  wrote on last edited by
                  #8

                  i think i get it...thks alot!

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups