Why allocate memory with the 'new' operator in c ++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why allocate memory with the 'new' operator in c ++?

what are the advantages and disadvantages of allocating Heap memory with 'new' instead of using the stack (declare variables in a traditional way and handle them without using pointers)? -Is my program going to be faster or slower? -It will take more or less memory -in which cases is it necessary to allocate memory with 'new'? thanks for the help :-) and sorry for my bad english xd

5th Sep 2017, 4:16 PM
Carlos Castillo
2 Answers
+ 2
Your program will be slower. Always prefer the stack or static variables over the heap when necessary. Allocating dynamic memory is very slow compared to the stack. It may make your executable smaller, since you are allocating the memory at runtime rather than compiler time. However, you still have to allocate/use space at compile time for pointers and dereferencing instructions. What it's used for: Dynamic memory is used for when you aren't sure how much memory you will need until runtime. Say for example, the user will input the size of an an array when they run your program. The heap can also be used to store data larger than the stack can handle, and a few other useful things. Finally, there is one major disadvantage to using new and delete. If you forget to delete the data or an exception is thrown before you delete it, you will leak the memory. This is why in modern C++, you should use vectors, smart pointers, or other similar containers that manage the memory for you with RAII.
5th Sep 2017, 8:29 PM
aklex
aklex - avatar
0
Hi thanks. Regarding the issue of memory release, I have another question: when allocating memory with the operator new and assigning values ​​to that memory space it is assumed that when you apply 'delete' on the pointer it erases the values ​​and frees memory right? . however, if we do this with a large data and we monitor the memory consumption by the task manager of the OS it is noted that the consumption remains the same even after applying 'delete'. I realized this by doing a slightly risky test with an infinite loop: while (1) {      new double; } The result is that the entire Ram fills up and the PC crashes. So why use new if the memory consumption is not lowered during program execution?
5th Sep 2017, 6:36 PM
Carlos Castillo