+ 1

malloc() and free() or new and delete ?

I learnt about memory managment in c and c++. I understood that malloc() and free() are used both in c and c++, new and delete are used only in c++. We can resize our memory with realloc() in c. And now I need more details. 1. Which of this commands (new, malloc()) is better to use in c++ programs? Any differences in performance or is it only for convinience? 2. Can we allocate memory with new and than realise with free()? 3. Can we use other c commands, realloc() for example, with new operator in c++ programs?

8th Jul 2020, 6:33 PM
Maksim - avatar
5 Answers
+ 2
With free(), you can only free memory that was allocated using malloc, calloc (or realloc). So you are not allowed to combine it with new... Same for realloc(), which also cannot be combined with new... There is moreover no equivalent for realloc() in c++..
8th Jul 2020, 6:54 PM
G B - avatar
+ 4
In the case of realloc(), Bjarne Stroustrup states that a standard library container like vector should be used instead.
8th Jul 2020, 9:06 PM
ChaoticDawg - avatar
8th Jul 2020, 6:43 PM
Maksim - avatar
+ 1
How can we realloc() memory in c++? Is not there any appropriate command?
8th Jul 2020, 6:55 PM
Maksim - avatar
1- It depend, but there is not any over head with new, delete. 2- What you mean ? new operator allocate memory and free() function (it's from libc) release it 3- You can overload new operator and use those c api's.
8th Jul 2020, 9:00 PM
قاسم رمضانی
قاسم رمضانی - avatar