N
N
Noortvel2016-01-04 22:54:41
Programming
Noortvel, 2016-01-04 22:54:41

Memory management in C++?

I'm learning C++. I decided to "quickly" jump from Java to C++, but I just can't figure out how to manage memory. I know that there is no garbage collector in C++, but what is garbage? (Google says that memory management these are pointers, but if I do this (see below), then only the pointer will be deleted, but not the variable itself? How then to delete the variable?)

int a = 3;
int *p = 0;
p = &a;
delete p;

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Peter, 2016-01-04
@Noortvel

There is no concept of "garbage" in C ++, since there should not be ownerless objects, if such appear, this is called a "memory leak".
There are 2 types of memory usage in C++.
1. On the stack. There is no need to allocate such memory in a special way and free it too.
Example:
2. In the heap. In this case, you are already responsible for allocating and freeing memory.
Works through the new operator. Or the malloc, calloc, etc. functions.

int* p = new int;
delete p;

V
Vladislav, 2016-01-04
@OnlyBooid

Let's try to figure out what you have written:
int a = 3; // declare a variable of type int
int *p = 0; // declare pointer
p = &a; // write the address of the variable a to the pointer
And now I suggest you write these simple lines to see what you still have stored there:
cout << "Value a=" << a << endl; //value of a
cout << "Address &a=" << &a << endl; //here address a
cout << "Value p=" << p << endl; //here is the address a
In your example, you do not need to delete anything, it will even cause an error during compilation, since the delete operator is used if you allocate memory dynamically, using the new keyword.
a case of you
int a = 3 // you allocated 4 bytes in memory;
int *p = you allocated (4 or 8 bytes to store address a, depending on whether you have a 32-bit or 64-bit system.
if you declare
int *p = new int //you are in dynamic memory allocate storage size int
delete p //deallocate the occupied memory location
I'm a beginner myself, and what I wrote here is my understanding, I would really like to be corrected.

V
Vladimir Martyanov, 2016-01-04
@vilgeforce

In general, if there is no special instruction to allocate memory (although the wording is lame, yes) - it is not necessary to release it specially. A special indication should be understood as new built into the language. And read the documentation for the functions used like malloc/VierualAlloc, etc. You don't use any functions and new means you don't need to specifically delete anything.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question