Search code examples
crealloc

Get memory corruption when using realloc function


#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int ind=0;

void rea(int* function)
{
    ind+=1;
    function = realloc(function,sizeof(int) * ind);
    function[ind-1] = 1;
}


int main(void) 
{
    int* fun = malloc(sizeof(int));
    int a =0;
    while(a<400)
    {
        int v = 0;

        rea(fun);
        puts("a");
        a+=1;
        ind+=1;
    }
}

I don't know why it gives me the error: double free or corruption Aborted (core dumped). I increment the ind every time and [ind-1] to assign the value so it shouldn't out of bound.


Solution

  • C is pass-by-value, means that any parameter passed at a function called is not passed by itself but its value is copied into another new variable of a compatible type. Thus when you call:

    rea(fun)
    

    the value of fun is used to initialize the function parameter. Any change to function has no impact on fun. As realloc may move the old memory chunk to a new place, if this happens then it is not reflected to fun. Alas when you call rea(fun) at a later time, you then pass a value that is no more usable, already freed by memory management system.

    A change may be:

    void rea(int** function) { // get the address of the pointer
        ind+=1;
        *function = realloc(*function,sizeof(int) * ind); // eventually modify the pointer at the given address
        (*function)[ind-1] = 1;
    }
    
    int main(void)  {
        int *fun = malloc(sizeof(int));
        int a = 0;
        while (a<400) {
            int v = 0;   
            rea(&fun); // pass address of the pointer
            puts("a");
            a+=1;
            ind+=1;
        }
    }
    

    -----EDIT-----

    realloc manual says, emphasize is mine

    The realloc() function tries to change the size of the allocation pointed to by ptr to size, and returns ptr. If there is not enough room to enlarge the memory allocation pointed to by ptr, realloc() creates a new allocation, copies as much of the old data pointed to by ptr as will fit to the new allocation, frees the old allocation, and returns a pointer to the allocated memory.