c - free() 函数给出 Core Dumped 错误

标签 c memory free mergesort calloc

我为合并排序写了一个简单的代码,但它给了我这个错误:

*** glibc detected *** ./merge: free(): invalid next size (fast): 0x09306058****Segmentation fault (core dumped)

这是代码:

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

void mergesort(int[], int, int);
void merge(int[], int, int, int);
void printarray(int[]);

int gs;
int main()
{
    int* a,i,s;
    printf("Enter size of the array\n");
    scanf("%d",&s);
    a = (int*)calloc(s,sizeof(int));
    gs = s;
    printf("Enter the array\n");
    for(i=0;i<s;i++)
    {
        scanf("%d",&a[i]);
    }

    printf("Showing the array\n");

    printarray(a);
    printf("\n");

    mergesort(a,0,s-1);

    printf("The sorted array is:\n");
    printarray(a);

    free(a);
    return 0;
}

void mergesort(int a[], int f, int l)
{
    int m;
    if(f<l)
    {
        m = (f+l)/2;
        mergesort(a,f,m);
        mergesort(a,m+1,l);
        merge(a,f,m,l);
    }
}

void merge(int a[], int f, int m, int l)
{
    int* t,i,j,h1,h2;
    t = (int*)calloc(l-f+1,sizeof(int));
    i = h1 = f;
    h2 = m+1;
    while(h1 <= m && h2 <= l)
    {
        if(a[h1] < a[h2])
        {
            t[i] = a[h1];
            h1++;
        }
        else
        {
            t[i] = a[h2];
            h2++;
        }
        i++;
    }

    if(h1>m)
    {
        for(j=h2; j<=l; j++)
        {
            t[i] = a[j];
            i++;
        }
    }
    else
    {
        for(j=h1; j<=m; j++)
        {
            t[i] = a[j];
            i++;
        }
    }

    for(j=f;j<=l;j++)
    a[j] = t[j];

    free(t);
    printarray(a);
}

void printarray(int a[])
{
    int i;
    for(i=0;i<gs;i++)
    printf("%d ",a[i]);
    printf("\n");
}

我认为错误出在 merge 函数中的 free(t) 行。由于某种原因,该 block 没有以应有的方式被释放。我该如何解决这个问题?

最佳答案

你的赋值超出了 t 的范围。

int maxIdx = f+l-1;
int * const t = (int*)calloc(maxIdx,sizeof(int));

while(h1 <= m && h2 <= l) {
    assert(h1 < gs);
    assert(h2 < gs);
    assert(i < maxIdx);
    if(a[h1] < a[h2]) {
        t[i] = a[h1];
        h1++;
    } else {
        t[i] = a[h2];
        h2++;
    }
    i++;
}

当我运行这个时:

Assertion failed: (i < maxIdx), function merge, file crash.c, line 59.

这正在发生 b/c l == 1 因此 i 比最大允许索引大 1。

关于c - free() 函数给出 Core Dumped 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12382019/

相关文章:

c - <stdatomic.h> 在 GCC 4.8 中?

C语法理解问题

c - C中的动态数组无法释放内存

Python 对文件夹中的文件进行操作 - 'for file in folder'

使用 Capifony 部署 Symfony2 项目时出现 PHP fatal error

c - 无法释放 C 指针

数据结构实现可以知道它是否在堆上吗?

python - 制作共享对象时,无法使用针对未定义隐藏符号 `__dso_handle' 的重定位 R_X86_64_PC32

c - 限制 CUBIST 条件参数

java - 如何解决 PermGen 内存问题