C Memory Management

前端 未结 12 1202
旧时难觅i
旧时难觅i 2020-11-30 16:54

I\'ve always heard that in C you have to really watch how you manage memory. And I\'m still beginning to learn C, but thus far, I have not had to do any memory managing rela

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 17:35

    Sure. If you create an object that exists outside of the scope you use it in. Here is a contrived example (bear in mind my syntax will be off; my C is rusty, but this example will still illustrate the concept):

    class MyClass
    {
       SomeOtherClass *myObject;
    
       public MyClass()
       {
          //The object is created when the class is constructed
          myObject = (SomeOtherClass*)malloc(sizeof(myObject));
       }
    
       public ~MyClass()
       {
          //The class is destructed
          //If you don't free the object here, you leak memory
          free(myObject);
       }
    
       public void SomeMemberFunction()
       {
          //Some use of the object
          myObject->SomeOperation();
       }
    
    
    };
    

    In this example, I'm using an object of type SomeOtherClass during the lifetime of MyClass. The SomeOtherClass object is used in several functions, so I've dynamically allocated the memory: the SomeOtherClass object is created when MyClass is created, used several times over the life of the object, and then freed once MyClass is freed.

    Obviously if this were real code, there would be no reason (aside from possibly stack memory consumption) to create myObject in this way, but this type of object creation/destruction becomes useful when you have a lot of objects, and want to finely control when they are created and destroyed (so that your application doesn't suck up 1GB of RAM for its entire lifetime, for example), and in a Windowed environment, this is pretty much mandatory, as objects that you create (buttons, say), need to exist well outside of any particular function's (or even class') scope.

提交回复
热议问题