使用 realloc 函数时出现内存损坏

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;
    }
}

我不知道为什么它会给我错误:双重释放或损坏已中止(核心已转储)。我每次都增加 ind 并 [ind-1] 分配值,所以它不应该越界。

C是按值传递的,意味着在调用的函数中传递的任何参数都不是自己传递的,而是将其值复制到另一个兼容类型的新变量中。因此,当您致电时:

rea(fun)

fun用于初始化function参数。对 function 的任何更改都不会影响 fun。由于 realloc 可能会将旧内存块移动到新位置,如果发生这种情况则不会反映到 fun。唉,当你稍后调用 rea(fun) 时,你传递了一个不再可用的值,它已经被内存管理系统释放了。

一个变化可能是:

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;
    }
}

-----编辑-----

realloc说明书说的,强调是我的

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.