Search code examples
c++memory-managementmallocnew-operatordynamic-allocation

What is Dynamic Memory Allocation in C++?


I'm learning about Dynamic Memory Allocation in C++ and the keywords new and new[] are mentioned. It is said to enable users to specify the size of the memory allocation at runtime, unlike simply declaring a variable or array with a fixed size in the source code.

I don't understand this concept. How does it work? I just need a clarification on the idea and an example would be helpful!


Solution

  • So, if you want an array of 10 integers, you'd be writing:

    int arr[10]; 
    

    But what if you wanted to do something like this;

    cout << "How many?";
    cin >> num;
    
    int arr[num];
    

    Well, the C++ language doesn't allow that. Instead, you have to do:

    int *arr = new int[num]; 
    

    to create your array. And later on you MUST[1] use:

    delete [] arr; 
    

    to free the memory.

    So, how does this work? When you call new, the C++ runtime library [the code that you didn't have to write that makes up the fundamentals of C++] will figure out how much space num integers take up, and find some space in memory for that. I'm not going into details of "how you find some memory". For now, just trust me, there is some memory available somewhere that can be used to store some integers in.

    When you later call delete, that same memory is given back to the "pool" or "heap" of memory that it came from.

    Of course, if you have a machine with, say, 256 MB of memory, and you try to ask for space to store 250 million integers, bearing in mind that an integer takes up more than one byte, it's not going to work out - there is no "magic" here - the memory is still limited to how much is available in the machine.... You just have the right to determine in the program, when it's running, how much memory you need, rather than having to decide when WRITING the program.

    Edit: It is generally best to "hide" any memory allocation using the already existing "container-" and "wrapper-classes" that are useful for this very purpose. For example:

     std::vector<int> arr;
    

    would work as a variable storage for integers, and you never have to worry about freeing the memory, or even knowing how many you need before you have stored them there.

     std::shared_ptr<int> arr = new int[num]; 
    

    is another case, where when the "shared_ptr" is no longer in use [it track that inside the shared pointer class, so you never need to care about freeing the memory].

    [1] If you don't want to leak memory, and it's "bad style" to leak memory. Not making anyone happy if you do.