Artaza Sameen
Artaza Sameen

Reputation: 787

Will it cause a memory leakage on using free() to deallocate a heap allocated variable by new operator?

int* integer = new int{10};
cout << *integer << endl;
free(integer);
cout << *integer << endl;

Output:

10
0

According to the code I've tested on my machine, It's quite obvious that the allocated memory is being successfully deallocated by using free()

But there are articles on the internet that discourages the use of the new operator and deallocation with free()

Are there any possibilities of memory leakage, if yes. Can anyone paste an example code where this type of leakage happens

Upvotes: 0

Views: 59

Answers (1)

eerorika
eerorika

Reputation: 238411

Will it cause a memory leakage on using free() to deallocate a heap allocated variable by new operator?

It will cause undefined behaviour. Technically, memory leak is included in the set of all behaviours and thus it can be part of any outcome, but the memory leak is really the least of your worries in this case.

Let me be clear: Don't ever call free on anything that wasn't returned by malloc (or the other related C functions).

Accessing the object after its lifetime and storage duration has ended also has undefined behaviour. Don't ever do that either.

Can anyone paste an example code where this type of leakage happens

Technically, you didn't delete what you new'd, so the program that you show is an example of program with memory leak. Interestingly, having undefined behaviour technically means that the memory leak doesn't necessarily happen. Regardless, you didn't demonstrate the lack of memory leak in your program, so there is no reason to assume that there isn't a leak.

The value pointed by a is set to 0. Why ?

Because the behaviour of the program is undefined.

And my code compiled fine

That's not a proof of lack of memory leak.

Upvotes: 1

Related Questions