Dynamic memory problem | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Dynamic memory problem

I just try to run two code one is simple that takes size of array during runtime And other takes size of array in run time using pointer, dynamic memory and new operator But both are working fine then why and when I have to use dynamic memory , new operator ? https://code.sololearn.com/cmXd4OeUejZj/?ref=app

8th Sep 2020, 9:33 AM
Mr Robot
Mr Robot - avatar
8 Answers
+ 3
In standard C++, variable length array is not allowed to be implemented in your first code. That is: int n = 10; int arr[n]; //Compile error. Then why the code is compiled you may ask. Because this is a g++ extension. It's only compileable when you compile with g++, and that's the compiler SoloLearn is using. So yes, you can do that in SoloLearn. But in other compiler it won't work. btw, in C variable length array is allowed. Whereas it is removed in C++.
8th Sep 2020, 9:48 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 4
The second example is more compatible than the first, the first uses a VLA (https://en.m.wikipedia.org/wiki/Variable-length_array), as I understand it, VLA is not widely implemented and may not be such a good idea (it can exhaust the stack when allocation is big). Don't forget to `delete [] ptr;` for the second example, allocated memory must be released again once we no longer use it.
8th Sep 2020, 9:44 AM
Ipang
+ 3
CarrieForle Ipang ~ swim ~ char arr[2000]; This array can cause memory issue in large programs , memory leaks and don't remove data from heap AND char* buffer = new char[2000] delete [] buffer; This prevent program from memory leaks and delete data from the heaps Is what I write above is true?
8th Sep 2020, 10:25 AM
Mr Robot
Mr Robot - avatar
+ 3
~ swim ~ so why we didn't simply use char arr[2000]; as it doesn't cause memory leaks? why we dynamically allocate data instead of automatically? I just started learning this today I am confused
8th Sep 2020, 10:36 AM
Mr Robot
Mr Robot - avatar
+ 3
~ swim ~ 😄 Thanks I am a solo learner watch youtube videos to learn no one to guide except this platform and you guys
8th Sep 2020, 10:57 AM
Mr Robot
Mr Robot - avatar
+ 2
Ipang OK bro thanks I am watching tutorials on dynamic memory but not study how to implement delete yet
8th Sep 2020, 10:00 AM
Mr Robot
Mr Robot - avatar
+ 1
CarrieForle OK thanks bro i understand it now . I just watching tutorials and practice it in solo learn
8th Sep 2020, 9:58 AM
Mr Robot
Mr Robot - avatar
+ 1
CarrieForle Ipang so in the first example if my code not runs successfully what we call this problem Did we called it "memory leaks"?
8th Sep 2020, 10:11 AM
Mr Robot
Mr Robot - avatar