1

I have question regarding memory management in c++ In below example is there any memory leakage. If so how to clear memory. Also defining int by * new is the only option to use and not int num = 25;

int main()
{
  for(int i = 0;i < 200;i++)
  {
    int num = * new int(25);
  }

I tried many ways but delete and free does not work

Mat
  • 202,337
  • 40
  • 393
  • 406
Niraj
  • 23
  • 2
  • 6
    `*new` is called the memory leak operator. It is an aberration. – Mat Nov 04 '22 at 08:54
  • you need to store the value returned by new in a pointer – Neil Butterworth Nov 04 '22 at 08:58
  • [r11-avoid-calling-new-and-delete-explicitly](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r11-avoid-calling-new-and-delete-explicitly) – Pepijn Kramer Nov 04 '22 at 08:58
  • new of one integer is overkill anyway, what are you trying to do? – Pepijn Kramer Nov 04 '22 at 08:59
  • 1
    and using new is not the "only option to use" - it is the very last one – Neil Butterworth Nov 04 '22 at 09:00
  • @NeilButterworth Yes it is! – Pepijn Kramer Nov 04 '22 at 09:07
  • Niraj where are you learning C++ from? Maybe your source is outdated and still showing a lot of code with new/delete in it. Or have you leared this in a datastructures class? (datastructure classes will teach about datastructures using C++, but they will not teach proper/current C++) – Pepijn Kramer Nov 04 '22 at 09:08
  • @Mat: I've never seen this construct (and for good reason by the sound of it). Is this a known antipattern ? Any idea how to google for this ? Edit: Ah, found something: https://stackoverflow.com/questions/46699180/usage-of-asterisk-before-newdynamic-allocation-in-c This might be a dupe for that, actually. – nick Nov 04 '22 at 09:11
  • 2
    Good explanations here: https://stackoverflow.com/questions/8839943/why-does-the-use-of-new-cause-memory-leaks @nick – Mat Nov 04 '22 at 09:17
  • 1
    @nick it is not an antipattern, it is a gross programming error. However the name *memory leak operator* precisely describes what happens here, that is to lose the pointer without storing it as soon as possible. – Jakob Stark Nov 04 '22 at 09:17
  • 4
    I'm wondering if this is a case of the "teacher using terrible code to illustrate a point" syndrome, and you're expected to do `int& num = *new int(25); delete &num;` which, despite being valid, nobody would ever do in the real world. – molbdnilo Nov 04 '22 at 09:20
  • 1
    why is `int num = 25;` not an option? In this case `int num = 25;` is memory managment done the right way – 463035818_is_not_an_ai Nov 04 '22 at 09:48

2 Answers2

1

is there any memory leakage

Yes. You created an int via new and immediately loose any reference to the pointer.

If so how to clear memory

You cant. num is just holds a copy of the value. You have no way to delete the actual int that was dynamically allocated.

Also defining int by * new is the only option to use and not int num = 25;

That makes no sense. Maybe there are things you didn't mention (odd requirements, weird assignment, or similar), but based on what you say, this is the correct way of "managing the memory":

for(int i = 0;i < 200;i++)
{
   int num = 25;
}

num has automatic storage duration. Its memory will be freed when it goes out of scope.

I tried many ways but delete and free does not work

For delete you need the pointer returned by new. You don't have that. Mixing free with new is wrong.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

OP: Also defining int by * new is the only option to use and not int num = 25;

No, in C++ you have different ways of create new data. In short, you can create new data automatically, dynamically or statically.

automatic storage duration

A a obj;

Here you're creating an object with automatic storage duration, this means, the object will be cleaned up when it goes out of scope. This object is created directly in the current active stack frame, so is directly accesible via identifier.

dynamic storage duration

Dynamic storaged objects are created with the new operator. This objects are stored on the heap, which is an unordered (mostly) region of memory reserved to handle heap allocations. The heap isn't able to talk with the stack regions directly, but we can communicate the stack and the heap program's data with pointers.

The new operator called in front on an object constructor, will perform a heap allocation, placing the value in some place of the heap and returning a pointer to the memory address where the value resides, available in the active stack.

A* a obj = new A();

Here, we are adquiring a resource that, as C++ developers, we must take care. So, when we end with our a object, we must tell the compiler that we finished with it and that piece of memory should be released or freed. We acomplish this in C++ with the delete keyword.

A* a obj = new A();

/* snip */

delete a;

If we don't delete the dynamically constructed resource, we will produce a memory leak. This is, we lose the access (the returned pointer) to the resource, and we can't no longer reach it. So, that resource w'd be using memory until the OS claim by itself that memory (and that's could also not happen), being in a undefined behaviour state, potentially leading to crashes and other things.

static storage duration

The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with static or extern

thread storage duration

The storage for the object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared thread_local have this storage duration. thread_local can appear together with static or extern to adjust linkage.

What's wrong with your code snippet?

int num = * new int(25);

You are dynamically initializing a variable with a value. This is because you are inmediatly dereferencing the pointer that the new operator returns, losing your access to the heap allocated variable. delete won't work, because you need a pointer type to apply the operator over it, and delete the resource beyond the pointer, that will be the result of the expression new int (25). This will return an int* that will store the address of the dynamically initialized integer.

Probably, you're looking for something like:

for(int i = 0;i < 200;i++)
{
   int* num = new int(25);
   /* snip */
   delete num;
}

TL;DR

Your deferencing, or following the pointer to the memory address that the new keyword applied on the int constructor returns to you, and then saving the value (not the pointer!) in the int num variable, losing the access to the heap allocated data, and causing a memory leak

Alex Vergara
  • 1,766
  • 1
  • 10
  • 29