Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Memory management

I've learned in College that you always have to free your unused Objects but not how you actually do it. For example structuring your code right and so on. Are there any general rules on how to handle pointers in C++?

I'm currently not allowed to use boost. I have to stick to pure c++ because the framework I'm using forbids any use of generics.

like image 385
Alexander Stolz Avatar asked Aug 26 '08 06:08

Alexander Stolz


People also ask

What is memory management in C language?

Dynamic memory management in C programming language is performed using the malloc() , calloc() , realloc() , and free() functions. These four functions are defined in the <stdlib.h> C standard library header file. It uses the heap space of the system memory.

Does C have automatic memory management?

Memory allocated on the heap, however, is treated differently by different languages. In C and C++, memory allocated on the heap is managed manually. In C# and Java, however, memory allocated on the heap is managed automatically.

How many memory management functions are there in C?

There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: malloc() calloc()

What are the memory types in C?

C Memory Model The C runtime memory model can be divided in to three types; global/static memory, the heap, and the stack. These all share the RAM available on the microcontroller.


1 Answers

I have worked with the embedded Symbian OS, which had an excellent system in place for this, based entirely on developer conventions.

  1. Only one object will ever own a pointer. By default this is the creator.
  2. Ownership can be passed on. To indicate passing of ownership, the object is passed as a pointer in the method signature (e.g. void Foo(Bar *zonk);).
  3. The owner will decide when to delete the object.
  4. To pass an object to a method just for use, the object is passed as a reference in the method signature (e.g. void Foo(Bat &zonk);).
  5. Non-owner classes may store references (never pointers) to objects they are given only when they can be certain that the owner will not destroy it during use.

Basically, if a class simply uses something, it uses a reference. If a class owns something, it uses a pointer.

This worked beautifully and was a pleasure to use. Memory issues were very rare.

like image 92
Sander Avatar answered Sep 22 '22 05:09

Sander