course content

Course Content

Introduction to C++

Allocating MemoryAllocating Memory

The memory inside a computer is clearly numbered, like the cells in a parcel machine.

When allocating memory for your data, you reserve a parcel locker cell for the size of your package. With the correct reservation of the cell, you will not have any problems, the package fit perfectly in size, and you did not overpay for unoccupied space. In case of incorrect cell reservation your parcel may not fit in size and you will not succeed or you will overpay for unoccupied space, because you have reserved a huge cell for a small parcel.

Memory allocation types

The C++ language supports 3 types of memory allocation:

  • static allocation - memory is allocated once for the entire duration of the program, for example, when we declare a variable or an array;

Example of static allocation:

The size of the variable/array must be known at compile time.

  • automatic memory allocation - such allocation works for function arguments and local variables;

Example of automatic memory allocation:

The resistance variable is local and exists only in the ValRes() function block, after the function has completed its work, the resistance variable is deleted. Allocating and freeing memory occurs automatically.

  • dynamic memory allocation - memory allocation while the program is running, let's consider this in more detail.

Dynamic memory allocation

The simplest example of a case where dynamic selection needs to be used is user input. For example, you have created a website, the user wants to register there, to do this, he needs to enter his name:

For the site of your school project, this is permissible, but in professional development (especially in embedded), this is an unacceptable practice.

If usernames, for example, one of the Eastern European regions will not exceed 15 characters, then we allocate memory twice as much as required, which means we lose memory.

Another example is games.

It would seem that your computer meets the requirements of the game, but the game still slows down. This is most likely due to poor optimization of the game itself and not because of your computer. The power of modern computers allows developers not to worry too much about optimization and memory-saving issues, so the game can take up many more resources on your PC than it actually needs.

For dynamic memory allocation, we need pointers.

Section 6.

Chapter 1