Thread: Dynamic memory allocation

Hybrid View

Previous Post Previous Post   Next Post Next Post
  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
    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

  4. #4
    Registered User
    Join Date
    Apr 2021
    Posts
    143
    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.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    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.

  6. #6
    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

  7. #7
    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

  8. #8
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,737
    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)

  9. #9
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,127
    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.

  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,737
    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 rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,127
    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 always best to free any memory you have allocated using, malloc(), calloc(), or realloc(), then using valgrind under Linux, you can double check for any allocations you missed, along with other memory errors. I use valgrind on all my code.

    The other issue with free is not setting the pointer to NULL after freeing the memory. You CANNOT access the memory after freeing it up!!! A better free() can help if consistently used:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void *free2(void *ptr);
    
    int main(void)
    {
       char *ptr = NULL;
    
       ptr = malloc(100);
    
       ptr = free2(ptr);
    
       /* Can also be called as with free():
          free2(ptr);
          ptr = NULL;
       */
    
       return 0;
    }
    
    void *free2(void *ptr)
    {
        free(ptr);
        return NULL;
    }
    This is the way free() should have been defined by Dennis!

  15. #15
    Registered User
    Join Date
    Sep 2018
    Posts
    217
    Quote Originally Posted by laserlight View Post
    and besides, the amount of memory available on the stack could be pretty limited.
    Did you mean to say that memory available in stack is limited compared to heap (I got this impression because the discussion was about allocating memory on the heap)?

    If so, why would that be? I had read that the stack and heap share the same memory space.. stack being at the top and growing downwards and heap being at the bottom and grouping upwards until they meet and there is no more memory left. So since they share the same memory space and grow until they can't.. they should have the same memory limit..

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