【问题标题】:Realloc corruption after some iteration C一些迭代 C 后的 Realloc 损坏
【发布时间】:2017-02-13 18:47:46
【问题描述】:

我正在尝试为函数中的结构指针数组动态分配内存。它可以工作到 3 次迭代,但在出现此错误后崩溃:

double free or corruption (fasttop): ...

这是我的结构指针数组声明:

Intersection** alreadyUse = malloc(sizeof(Intersection*));

if(alreadyUse == NULL) {
   exit(1);
}

int size = 1;
alreadyUse[0] = inter; // Pointer of an Intersection

// Some Code

checkFunction(alreadyUse, &size, interLeft);

这是我的功能

bool checkFunction(Intersection** alreadyUse, int* size, Intersection* inter) {

    for(int i = 0; i < *size; i++) {
        if(alreadyUse[i] == inter) {
            return true;
        }
    }

    *size = *size +1;
    Intersection** tmp = realloc(alreadyUse, sizeof(Intersection*) * *size);

    if(tmp == NULL){
        exit(1);
    }
    else {
        alreadyUse = tmp;
    }

    alreadyUse[*size-1] = inter;

    return false;
}

正如我所说,它适用于 1、2、3,然后我得到错误。

是否有人知道它为什么会起作用然后突然崩溃?

感谢您的帮助。

【问题讨论】:

  • 我们不知道 Intersection 类型

标签: c pointers malloc realloc memory-corruption


【解决方案1】:

您在checkFunction 中更改alreadyUse 的值。但这对调用者没有影响。如果对realloc 的调用实际上重新分配,调用者仍然有一个指向现在已被释放的旧块的指针。

【讨论】:

    【解决方案2】:

    在这个函数调用中

    checkFunction(alreadyUse, &size, interLeft);
    

    变量size 是通过引用传递的。所以可以在函数中更改。但是,正如您所见,变量 alreadyUse 不是通过引用传递的。因此,该函数处理变量值的副本。如果您希望在函数中更改变量,则必须通过引用传递它

    checkFunction( &alreadyUse, &size, interLeft);
                   ^^^^^^^^^^^
    

    因此函数应该被声明为

    bool checkFunction(Intersection*** alreadyUse, int* size, Intersection* inter);
                       ^^^^^^^^^^^^^^^
    

    函数定义可以是这样的

    bool checkFunction( Intersection ***alreadyUse, int *size, Intersection *inter ) 
    {
        for ( int i = 0; i < *size; i++ ) 
        {
            if ( alreadyUse[0][i] == inter ) return true;
        }
    
        Intersection **tmp = realloc( alreadyUse[0], sizeof( Intersection * ) * ( *size + 1 ) );
    
        if ( tmp == NULL ) exit( 1 );
    
        alreadyUse[0] = tmp;
    
        alreadyUse[0][( *size )++] = inter;
    
        return false;
    }
    

    【讨论】:

    • size 是“通过引用”传递的,这是令人困惑和不准确的,因为 C 是一种纯粹的按值传递语言。指向size 的指针按值传递。
    • @DavidSchwartz 引用术语在 C 语言中是有效且准确的,例如“指针类型描述了一个对象,其值提供对被引用类型实体的引用”。
    • 也许:“...传递了对size引用 ...”
    • @VladfromMoscow 谢谢!有用。我以为指针是通过引用传递的,但显然我错了。
    • @Tsuuki 完全没有。:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2020-10-26
    相关资源
    最近更新 更多