Why do we need dynamic memory allocation in C++?

Hello, Greetings; hope you all are fine, safe and doing well.

I am doing my BSSE through course material it does not make any sense to me Why do we need dynamic memory allocation in C++?

Why it does not make any sense to me?
Well, we can do same thing without using dynamic memory allocation so why to do that!


From our teacher this example was given!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main() {
	int num;
	int *pArray;
	cout << "Enter size of array:";
	cin >> num;
	pArray = new int[num];
	for (int i = 0; i < num; i++)
	{
		pArray[i] = i + 1;
	}
	for (int i = 0; i < num; i++)
	{
		cout<<pArray[i];
	}
	cout << endl;
	return 0;
}//end of the main 


We can archive same things by doing something like this

int pArray[num];
And we will remove the int *pArray;

Here is the whole code become

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main() {
	int num;
	//int *pArray;
	cout << "Enter size of array:";
	cin >> num;
	int pArray[num];
	for (int i = 0; i < num; i++)
	{
		pArray[i] = i + 1;
	}
	for (int i = 0; i < num; i++)
	{
		cout<<pArray[i];
	}
	cout << endl;
	return 0;
}//end of the main 


Does it make any sense to you, hopefully not at all!

My Question here is what are the real world example, scenario or situations where we need dynamic memory allocation. [nstead of just learning syntax i think it better to also study application as well, so i am here to ask like that question.

Thanks you so much for your time.
Last edited on
That doesn’t actually work. num has to be a constant expression. For that to work, and cining it automatically makes it not constant.
Last edited on
@highwayman

Both programs works fine

First
http://cpp.sh/8auwb

Second
http://cpp.sh/4e25z
1
2
cin >> num;
int pArray[num];
The thing is, you can't do that. It's not legal standard C++; highwayman is correct. GCC has an extension that it has on by default to allow it, but it has drawbacks regardless.

Let's say it were legal for purposes of argument. Even so, Variable-Length Arrays (VLAs) are allocated on the stack, which is relatively small in capacity (could be ~8 MB in size, by default). If you put too many arrays like this on the stack, you will get a stack overflow, which is usually not recoverable.

Using "the heap" gives you gigabytes of space to work with, not a few megabytes.
Also, in general, using dynamic memory allows you to extend the lifetime of an object outside of the scope it's defined in.

For example, instead of returning a large object, you can just return a pointer to this large object that lives in dynamic memory. Of course, using pointers in "modern C++" is discouraged when not needed. The compiler can optimize away the copy in many cases, or at least use move semantics when dealing with things that are essentially wrappers for pointers, e.g. std::vector.
Last edited on
is it a complaint about syntax?
lets say it was actually legal and dynamic, that c++ compiler was coded to get a blob off the heap for your array and that it auto released the memory when it went out of scope; both easily doable.

it would still be dynamic memory, but hidden from you. We have that already, its called a vector -- it hides what it is doing from you, but its still doing it.

So a few answers are..
- we need dynamic memory because operating systems and even hardware to some extent are designed in a way that makes it a useful tool.
- c++ has dynamic memory because it allows coding at both high and low levels. Even with all our modern tools, you can, if you choose, do it yourself if you have some reason to do so. Modern c++ does not do a lot of dynamic memory outside of special purpose software, but its there if you want it.
- hiding the details from the user isn't always the most efficient code. C++ at its core is still a tool for performance, and sometimes, doing it yourself is faster
- the other languages have dynamic memory too, they just hide as noted above. Its not like its not there, asking the os for memory and giving it back, its just doing it when you are not looking, stealing your cpu cycles.

all that is on top of the code you posted being an unsupported extension.

A real world example of dynamic memory?
Every stl container uses it. Writing without the STL … sure, its called C -- or C++ from the early 1990s. Its no longer really acceptable to do that outside of things like the implementation of vector itself, assuming that is in C or C++ when it is built which may vary by compiler vendor. Most programs will use dynamic memory just because the language uses it in its toolset, and in that regard, its becoming more like java and friends every iteration. A real world problem where you do dynamic memory yourself? Maybe that is the true question... the answer is, its rare. We don't need it, because the things that use it most are containers, and c++ now has containers that do the memory management for us. Its not necessary very often anymore.

Last edited on
Solved, thanks you so much all of you
Another point to consider:
1
2
3
4
5
6
data* return_data()
{
    data d;
    return &d;    //ERROR: data is destructed at the end of return_data and its memory is deallocated! 
                        //You now return an invalid pointer to data that doesn't exist anymore.
}


1
2
3
4
5
data* return_data()
{
    return new data;    //No error. Data is allocated dynamically, which means it doesn't live on a stack frame
                                 //and therefore it isn't destructed at the end of return_data();
}
Topic archived. No new replies allowed.