Thread: How memory reallocation work

  1. #1
    Registered User
    Join Date
    Oct 2022
    Posts
    92

    How memory reallocation work

    Hello everyone,
    I'm trying to understand the concept of dynamic memory allocation and reallocation in C, specifically how the realloc function works. Let me illustrate my confusion with an example:
    Suppose initially allocate dynamic memory for three variables with values 30, 31, and 32, resulting in memory locations 30, 31, and 32. Now, if I want to add two extra numbers but find that memory locations 33 and 34 are already occupied by other variables, and memory are available from 35 location.

    What happens when I use the realloc function? How does it handle the situation where the desired memory locations are already in use?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > How does it handle the situation where the desired memory locations are already in use?
    It's better you think realloc as always moving the memory to a new location.
    Code:
    void *realloc(void *ptr, size_t size) {
        void *new = malloc(size);
        if ( new ) {
            memcpy(new, ptr, min(oldsize,size) );
            free(ptr);
        }
        return new;
    }
    In fact, some debug versions will force it to move every time.

    Leaving the memory where it currently is is an optimisation.
    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.

  3. #3
    Registered User
    Join Date
    Apr 2021
    Posts
    140
    Quote Originally Posted by Kittu20 View Post

    What happens when I use the realloc function? How does it handle the situation where the desired memory locations are already in use?
    I don't know about the writing, but there are pictures in this article that illustrate the two successful cases of realloc working: The realloc() Function in C - C Programming Tutorial - OverIQ.com

    The short version is this: realloc checks the "internal records" of the allocation system to see if the memory block you are using can be expanded in-place. If not, then it looks for a memory block that is large enough to satisfy your new size. If it finds, or can obtain from the OS, such a block, then it "copies" your existing memory block over to the new location, marks the old location as free(), and returns a pointer to the new block. If it cannot find such a block, then it returns NULL, leaving your original block unmodified.

    As a caller of realloc, you have to deal with these cases:

    1. realloc returns the same block pointer, but there is more space available in that location. The old pointer is still valid, and any pointers into the old block are still valid.
    2. realloc returns a different block pointer, with more space available. The old pointer is no longer valid. Any pointers into the old block are invalid.
    3. realloc returns NULL. This suggests that calls to malloc will also return NULL for the same size. The old pointer is still valid, but no additional space is available. Any pointers into the old block are still valid.

    It is absolutely not recommended to use realloc on an object that will have pointers taken to inside parts. Either you should use only data types that do not provide interior pointers, or you should rely instead on indexes or relative pointers. (A relative pointer is just an index with a different base type ;-)

    Because realloc can fail, you must account for that case. If you are still learning C, the most reasonable behavior is probably "samurai mode." Just write yourself a library that exports functions like sm_realloc that do the exact same job, but which print a message and exit if a failure occurs. On the other hand, if you are writing a serious application like a text editor, the fact that the system is still in the same state after a failed call to realloc means you can possibly recover from the error (by closing buffers, say) or you could gracefully save all the files and exit, if necessary.
    Last edited by aghast; 01-16-2024 at 11:24 AM. Reason: typos

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory reallocation
    By Ducky in forum C++ Programming
    Replies: 21
    Last Post: 06-14-2013, 12:03 PM
  2. reallocation of heap memory
    By sukhdeep in forum C++ Programming
    Replies: 17
    Last Post: 12-20-2011, 02:16 AM
  3. Memory allocation/reallocation
    By magda3227 in forum C Programming
    Replies: 10
    Last Post: 07-04-2008, 03:27 PM
  4. Memory reallocation in C++
    By spank in forum C++ Programming
    Replies: 2
    Last Post: 08-08-2007, 09:56 AM
  5. Dynamic memory reallocation
    By Gravedigga in forum C++ Programming
    Replies: 6
    Last Post: 05-15-2005, 06:39 PM

Tags for this Thread