C 编程使用 free() 时出现“分段错误(核心转储)”[重复]

问题描述 投票:0回答:3

我正在尝试创建一个二维数组,但是当我在程序末尾使用 free 时,我总是收到“分段错误(核心转储)”错误。使用sleep函数只是因为我想看看它是否在创建数组后或之后崩溃,而我一使用free(array)程序就崩溃了

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


void check(int number)
{
    if(number < 0)
    {
        fprintf(stderr, "You cannot use a value below zero!\n");
    }
}


int create_array(int **array, int size)
{
    array = (int**)malloc(size * sizeof(int*));

    for(int i = 0; i < size; i++)
    {
        array[i] = (int*)malloc(size * sizeof(int));
    }

    printf("Successfully created the array!\n");
    printf("The size of the array is %d * %d = %d", size, size, sizeof(array) / sizeof(int));

    return EXIT_SUCCESS;
}


int main(void)
{
    int N;
    printf("Please enter a value for N: ");
    scanf("%d", & N);
    check(N);

    int R;
    printf("Please enter a value for R: ");
    scanf("%d", & R);
    check(R);

    int **array;
    create_array(array, N);
    sleep(1);
    free(array);

    return EXIT_SUCCESS;
}
c segmentation-fault malloc free coredump
3个回答
1
投票

您仅在

array
函数中修改
create_array()
的本地副本。为了能够修改 main() 中的指针
array
,您需要向其传递一个指针(即该函数需要接收一个
int***
)。

更简单地说,您可以从函数中返回

array
并将其分配给main()中的
array
,并且不需要传递第一个参数。


1
投票

您正在创建动态数组,但您没有返回该数组的引用,这就是您无法释放它的原因。


0
投票

您需要拨打

create_array()
,如下:

int **array;
create_array( &array, N);

然后将其定义为:

int create_array(int*** array, int size)
{
    *array = (int**)malloc(size * sizeof(int*));

    for(int i = 0; i < size; i++)
    {
        (*array)[i] = (int*)malloc(size * sizeof(int));
    }

    printf("Successfully created the array!\n");
    printf("The size of the array is %d * %d = %d", size, size, sizeof(array) / sizeof(int));

    return EXIT_SUCCESS;
}

但是,您仍然会出现内存泄漏,因为您只释放

array
而不是将
array[0]
释放到
array[N-1]
。创建相应的
destroy_array()
函数会更安全。

© www.soinside.com 2019 - 2024. All rights reserved.