+ 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?
5 Antworten
+ 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++..
+ 4
In the case of realloc(), Bjarne Stroustrup states that a standard library container like vector should be used instead.
https://www.stroustrup.com/bs_faq2.html#renew
+ 2
Already found the answer on first question:
https://www.geeksforgeeks.org/new-vs-malloc-and-free-vs-delete-in-c/?ref=rp
+ 1
How can we realloc() memory in c++? Is not there any appropriate command?
0
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.