Thread: Dynamic memory allocation

  1. #1
    Registered User
    Join Date
    May 2021
    Posts
    66

    Dynamic memory allocation

    Hello everyone

    I do not understand what is dynamic memory allocation in programming. I have read many tutorials and have read the topics given in the books but I am not able to understand clearly.

    I know dynamic memory allocation at runtime. It is said that when we do not know how much memory will be required, then we should use dynamic memory. But this is not understandable to me because to store any record we should know about its size.

    Can anyone clarify why it say when we don't know how much memory we need then we should use dynamic memory

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Pointers in C - Cprogramming.com

    The above link might help.

    The words "stack" and "heap" are important to understand.

    And, you need to know when the program will know the size at compilation or at run-time.

    If the size is not know at compilation; but, it going to be know at run-time then it is normal to use dynamic memory allocation.

    Tim S.
    Last edited by stahta01; 08-26-2021 at 02:14 AM. Reason: Add more info
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Just try reading a file into memory.

    You don't know how many lines there are.
    You don't know how long each line is.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    May 2021
    Posts
    66
    >"If the size is not know at compilation; but, it going to be know at run-time then it is normal to use dynamic memory allocation."

    This is the main key point of my problem

    Whenever I start writing a program, it becomes necessary for me, I need to know first how many variables I have to store. Like if I want to store Integer, first thing comes to my mind is how many Integer values ​​I have to store. If i want to store more than one integer i will use array If I want to store 10 integers then the size will be 10

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Rahul11
    Whenever I start writing a program, it becomes necessary for me, I need to know first how many variables I have to store. Like if I want to store Integer, first thing comes to my mind is how many Integer values ​​I have to store. If i want to store more than one integer i will use array If I want to store 10 integers then the size will be 10
    Salem already provided the example of reading a file.

    You're right to say that if you want to store 10 integers then the size will be 10. Dynamic memory allocation comes into play when you want to store n integers, such that you don't know what is the value of n beforehand. There are plenty of reasons why you might not know the value of n beforehand. For example, maybe different users will have different needs. Or maybe the same user might only want to record a small number of values on one day, but a large number of values on another day. Or maybe the user does not know how many values they want to record... it depends on circumstances beyond your control.

    Of course, you might say "I'll allocate as much memory as anyone will ever need!" But that runs into the problem that this could be "all the memory available", and besides, the amount of memory available on the stack could be pretty limited.
    Last edited by laserlight; 08-26-2021 at 05:14 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,733
    Quote Originally Posted by Rahul11 View Post
    Hello everyone

    I do not understand what is dynamic memory allocation in programming. I have read many tutorials and have read the topics given in the books but I am not able to understand clearly.

    I know dynamic memory allocation at runtime. It is said that when we do not know how much memory will be required, then we should use dynamic memory. But this is not understandable to me because to store any record we should know about its size.

    Can anyone clarify why it say when we don't know how much memory we need then we should use dynamic memory
    Peops have said the answer in various ways but I suspect that those weren't clear enough for you, the simplest difference between fixed and dynamic memory is this, fixed memory is allocated prior to code execution via compiled in instructions or loader calls, it should never be manually free'd, dynamic memory is memory you allocate manually as the compiler either could not or would not take care of this process for you, dynamic memory also must be manually free'd at some point before the process terminates (this also happens for fixed memory but the compiler has already dealt with the complexities involved with it), failure to do so leaves less resources for future instances and can even cause an system to panic and shutdown in rare cases (rare because modern systems are designed to be able to forcefully take back resources, this does not mean you can be callous however as there are limits to what leaks a system can detect, for example memory allocated on the graphics card/gpu is much harder to cleanup than on paged memory as on paged memory the system is able to check what processes no longer exist out of assigned memory and force release if it doesn't, this does have a limitation in that if a new process was spawned to hold the same ID then the system may think that process assigned the memory and never provide it when it could've been)

  7. #7
    Registered User
    Join Date
    Apr 2021
    Posts
    139
    Suppose you are reading data from a file.

    The data are in records. Each record includes name, address, postal code, phone, etc., mostly on separate lines.

    The first line of the file is an integer that indicates how many records.

    At compilation time, you don't know what the filename is, how many records there are, how long the various strings are, or anything else.

    This is pretty normal for computer programs. Dynamic allocation is really the default, not the exception.

    If you want to see more examples like this, try one of the code gamification sites. They're chock full of "first line contains N, the number of ..." type problems to solve.

  8. #8
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,110
    Quote Originally Posted by Rahul11 View Post
    Hello everyone

    I do not understand what is dynamic memory allocation in programming. I have read many tutorials and have read the topics given in the books but I am not able to understand clearly.

    I know dynamic memory allocation at runtime. It is said that when we do not know how much memory will be required, then we should use dynamic memory. But this is not understandable to me because to store any record we should know about its size.

    Can anyone clarify why it say when we don't know how much memory we need then we should use dynamic memory
    Short of taking a course in C Programming from a qualified instructor, you need to study a good book on the C Programming Language, cover to cover, and do all the exercises at the end of each chapter! Choose one of the three listed below:

    C Programming, A Modern Approach
    Author: K. N. King

    C Primer Plus, 6th Edition
    Stephen Prata

    C How to Program, 8/e
    Deitel & Deitel

    Please avoid any painfully inadequate online YouTube videos, or equally inadequate so-called, "tutorials". You will only get part of what you need to know, or worse, incorrect information.

  9. #9
    Registered User
    Join Date
    May 2021
    Posts
    66
    I think I almost understood when to use dynamic memory. If there is some mistake in my understanding please correct me.

    Dynamic memory is used when we do not know really how much memory we need. If we have allocated more memory than required, we are just wasting memory. If we allocate less memory than required, the system will not be able to save the record.

    For example, if i have to store the marks of a student in a school. I should definitely allocate dynamic memory because I don't know how many students are in the school.

    If I allocate static memory for 200 students, then It will waste of memory if there are only 100 students in the school. if I allocate static memory for 50 students. It would be fail because I haven't allocate enough memory.

    If I did allocate dynamic memory for 50 students and later I come to know that there are 50 more students then I can allocate memory space again for 50 students.

    This is all my understanding for dynamic memory allocation i have explain in details. Please clarify if I have misunderstood the basic concepts somewhere.

    Thank you all for your great help

  10. #10
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Dynamic memory means you can change the amount of memory at run-time. Non dynamic called by you static memory (I do not consider this 100 percent correct) is fixed/set at compile time. As you write bigger programs you will understand the need to use dynamic memory more; I know I understood it when I created my first link list. Big programs that require a lot of memory use dynamic memory partly so it can be freed when it is no longer needed. This makes it easier for more than one program to run at the same time.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  11. #11
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,733
    Just as a side note it is usually best to maintain a list of allocated memory blocks, easier to ensure all are free'd before termination in the event it was missed elsewhere or you simply wanted to save some time by keeping memory allocated and just passing it onto the next thing that want's it.

  12. #12
    Registered User
    Join Date
    Sep 2020
    Posts
    425
    Quote Originally Posted by awsdert View Post
    Just as a side note it is usually best to maintain a list of allocated memory blocks, easier to ensure all are free'd before termination in the event it was missed elsewhere or you simply wanted to save some time by keeping memory allocated and just passing it onto the next thing that want's it.
    I strongly disagree with this advice. "Maintaining a lost of allocated memory blocks" is exactly what malloc(), free(), realloc() and so on do on the inside, and usually do it in a far more nuanced way than any of us ever will. For example, large allocations may be "memory mapped" blocks, where small allocations come off of a traditional heap. IIRC the current Linux glibc malloc() runs multiple heaps (called "arenas") allowing multiple threads to perform memory allocation at the same time in a thread-safe manner.

    You are far better using memory-safe coding patterns to ensure everything that is allocated gets freed, and using tools like "valgrind" to ensure that you don't have memory leaks, than to implement workarounds.

    Well, that's my opinion anyway.

  13. #13
    Registered User
    Join Date
    Sep 2018
    Posts
    217
    Quote Originally Posted by awsdert View Post
    Just as a side note it is usually best to maintain a list of allocated memory blocks, easier to ensure all are free'd before termination in the event it was missed elsewhere or you simply wanted to save some time by keeping memory allocated and just passing it onto the next thing that want's it.
    Is it necessary to call free() when you're about to reach program termination? The entire program is about to be unloaded anyway..

  14. #14
    Registered User
    Join Date
    Sep 2020
    Posts
    425
    Quote Originally Posted by Nwb View Post
    Is it necessary to call free() when you're about to reach program termination? The entire program is about to be unloaded anyway..
    It is very hard to track down if you mave a memory leak in your code if it doesn't free all resources before exiting.

    Also, usually tidying up before exiting can involve such things as writing buffers with changed data to disk, so finishing in a haphazard way may result in data loss.

    But then again you might be writing missile guidance systems, where exiting cleanly might not be a concern...

  15. #15
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,733
    Quote Originally Posted by hamster_nz View Post
    It is very hard to track down if you mave a memory leak in your code if it doesn't free all resources before exiting.

    Also, usually tidying up before exiting can involve such things as writing buffers with changed data to disk, so finishing in a haphazard way may result in data loss.

    But then again you might be writing missile guidance systems, where exiting cleanly might not be a concern...
    That's not the kinda cleanup I was referring to, for files I just close them, if there was data to be written I ignore it, better a cleanly corrupted file that is easy to recover from than one with an arbitrary stopping point that is not so easy to recover from (for example the file might require each line to be complete and the code using it might be designed to flush the buffer whenever there is not enough room for the next line, better to loose the few extra than potentially write an incomplete line at the end), as for data you can report memory that is still reporting as in use before you free it, this gives a cleaner way of catching those faults in the event your code is somehow running on a system that isn't smart enough to force free memory of terminating processes (or the process happens to be zombified which I've had happen on rare occasions), another reason for doing it is perhaps you're running on windows or dos where there are definitely versions that don't manage to force free all the memory a process used (I had to restart my computer a few times because of that even on windows 10), a good fallback is always better than an assumed fallback, at least if an assumed fallback is not enough or non-existent then the good fallback will help lessen the severity before it gets there. As a nice side effect it part of the code can always be abstracted into list management functions that can be used for all the various structs and classes that one designs, further it becomes easier to catch when a buffer is released to early if all you need to pass around is a list of buffers and the index of the list your code is supposed to be using, if it gets deactivated somewhere in code and later code then requests access to the object via a function that function can return NULL instead of the buffer object and subsequent code can either error out or segfault, erroring out is a better than segfaulting because developing the habit of erroring out makes it easier to experiment with kernel code later if you so feel like it, there's also the situation where you want to program for older devices that cannot support operating systems, always better to have the habit of writing code that has last resorts than to assume the system can cleanup your mess without shutting down.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what is dynamic memory allocation
    By dbzx in forum C Programming
    Replies: 7
    Last Post: 06-08-2009, 08:11 AM
  2. Dynamic Memory Allocation
    By schifers in forum C Programming
    Replies: 12
    Last Post: 05-14-2008, 01:49 PM
  3. Memory dynamic allocation
    By elvio.vicosa in forum C Programming
    Replies: 8
    Last Post: 10-16-2007, 03:30 AM
  4. Help with dynamic memory allocation
    By malooch in forum C Programming
    Replies: 2
    Last Post: 12-13-2006, 01:26 PM
  5. Dynamic memory allocation
    By amdeffen in forum C++ Programming
    Replies: 21
    Last Post: 04-29-2004, 08:09 PM

Tags for this Thread