Open In App
Related Articles

C++ Program that will fill whole memory

Improve Article
Improve
Save Article
Save
Like Article
Like

NOTE:We strongly recommend to try this code in virtual machine because it may hang your computer within 5 second

Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer. Dynamically allocated memory is allocated on Heap and non-static and local variables get memory allocated on Stack

new Keyword
The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

Syntax to use new operator: To allocate memory of any data type, the syntax is

pointer-variable = new data-type;

delete Keyword
delete that perform the task of allocating and freeing the memory in a better and easier way.

Syntax to use delete operator: To allocate memory of any data type, the syntax is

delete pointer-variable; 

Following is C++ Program that will fill whole memory




#include<bits/stdc++.h>
  
int main()
{
    while (true)
      int *a = new int// allocating 
}
  


Output & Explanation
It hung my computer while the task manager was open and showed that it took 890 Mb of memory in 1 second then it also hung. It keeps on giving memory to a variable.To explore more of this code, added a statement delete a and every thing was fine while testing (no hanging) So, I think that the chunk of memory is given (due to new int) and then taken back (due to delete a) to the free space in the new code below.

Mitigated Code




#include<bits/stdc++.h>
int main()
{
    while (true)
    {
         int *a = new int;   // allocating
         delete a;           // deallocating
    }
}  


References
https://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 15 Aug, 2017
Like Article
Save Article
Previous
Next
Similar Reads