Thread: Naive Realloc Implementation Seg faults

  1. #1
    Registered User
    Join Date
    May 2016
    Posts
    104

    Naive Realloc Implementation Seg faults

    I need to use a re-sizable buffer. For academic reasons I am not allowed to use realloc, not yet anyway, so I made a simple naive local implementation that simply uses malloc to allocate a new memory area of size n, and copies the bytes of the old buffer to it. Then frees the old memory, and returns a pointer to the newly created buffer.

    I know this is far from optimal and causes memory fragmentation but it's all I can do for now.

    I increase my buffer by calling my realloc and doubling it's size on each iteration. e.g I start with a buffer of 32 bytes, if I need more space, I call realloc and double that to 64 and so on.

    The problem is that my realloc always crashes on the second call, right after trying to free the old memory.

    Why could this be? I'd appreciate any help. Thanks
    Code:
    static void     *my_realloc(void *mem, size_t size)
    {
            char    *new_mem;
            char    *old_mem;
    
    
            if (!mem || !size)
                    return ((void*)0);
            new_mem = (char*)ft_memalloc(size * sizeof(char));
            if (!new_mem)
                    return ((void*)0);
            old_mem = mem;
            while (*old_mem)
                    *new_mem++ = *old_mem++;
            free(mem);
            return (new_mem);
    }
    Crash occurs on free(mem), always on the second call.

    To further illustrate, this is an example context of how I'm using the function:
    Code:
    ....
    const size_t buffer_size = 32;
    char *buffer = (char*)malloc(buffer_size * sizeof(char) + 1);
    while (...)
    {
        buffer = (char*)my_realloc(buffer, current_buff_size += buffer_size);
        ....
    }
    Last edited by Dren; 05-25-2018 at 11:50 PM. Reason: use cases examples

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,498
    Your copy loop assumes \0 terminated strings, but doesn't even copy the \0.
    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
    May 2016
    Posts
    104
    Quote Originally Posted by Salem View Post
    Your copy loop assumes \0 terminated strings, but doesn't even copy the \0.
    I don't copy the null because the new memory area is already filled with /0. Courtesy of the proxy function I use instead of malloc; basically it calls malloc and does a bzero on the result, before returning.
    For more information, this is the instruction the debugger stops at: addq $0x88, %rsp and this is the exact error I get munmap_chunk(): invalid pointer
    Last edited by Dren; 05-26-2018 at 01:26 AM.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,498
    But in your example, your initial bootstrap function is malloc, which has undefined contents.
    It could be a long while in the copy loop before it stumbles into a \0.

    A proper realloc KNOWS the old size of memory. It doesn't have to guess the size by looking at the contents.

    > current_buff_size += buffer_size
    1. Don't try and make your code too cute by compressing lines like this.
    2. You need to make it consistent with the original allocation, which has a mysterious +1, that is lost.

    Code:
    const size_t buffer_size = 32;
    size_t current_buff_size = buffer_size;
    char *buffer = (char*)malloc(current_buff_size);
    while (...)
    {
        temp = (char*)my_realloc(buffer, current_buff_size + buffer_size);
        if ( temp != NULL ) {
            // only update the size on success.
            buffer = temp;
            current_buff_size += buffer_size;
        } else {
            // do something with buffer and the original value of current_buff_size
        }
        ....
    }
    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.

  5. #5
    Registered User
    Join Date
    May 2016
    Posts
    104
    My example was a half-assed attempt to illustrate how I would use the function. I assure you except for the "cute" current_buff_size += buffer_size, it looks nothing like my actual code, I apologize for the confusion.
    Still, I can take a hint and will look with more detail into my calling code, and perhaps create a new simple test code to isolate the call, as your replies seem to indicate you believe that is where the error is, whereas I thought, it was related to freeing the pointer. It'll have to wait til' tomorrow, too tired now to think straight.

    Thanks for the replies :thumbsup

  6. #6
    Registered User
    Join Date
    May 2016
    Posts
    104
    Thank you Salem.:heart:
    As you originally pointed, the problem was within the /0. Turns out I was using all the buffer leaving no room for the null terminating char at the end and so, ended up reading memory outside its boundaries. Not enough to crash the program right away, but sufficient to cause other mayhem.
    To prevent this in the future, I followed your advice and pass the old memory size along with the size to allocate, and use that to control the copy instead of looking through the contents of the pointer.

    Kudos man!



    PS:Stepping through a few iterations with the debugger shows that old memory get's eventually reused; I guess malloc is pretty smart and mem fragmentation won't be as bad as I thought.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 03-26-2014, 07:41 PM
  2. naive print bits function
    By monkey_c_monkey in forum C++ Programming
    Replies: 15
    Last Post: 08-05-2012, 03:06 PM
  3. Seg Faults with XOR LL
    By seePhor in forum C Programming
    Replies: 5
    Last Post: 03-12-2010, 12:20 AM
  4. It seg faults right away
    By Brimak86 in forum C Programming
    Replies: 6
    Last Post: 01-31-2008, 10:40 PM
  5. It seg faults
    By Brimak86 in forum C Programming
    Replies: 2
    Last Post: 01-15-2008, 09:06 PM

Tags for this Thread