C 编程使用 free() 时出现 "Segmentation fault (core dumped)"

标签 c segmentation-fault malloc free core

我正在尝试创建一个二维数组,但是当我在程序末尾使用 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;
}

最佳答案

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

更简单地说,您可以返回 array从函数中并将其分配array在 main() 中,您不需要传递第一个参数。

关于C 编程使用 free() 时出现 "Segmentation fault (core dumped)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41911187/

相关文章:

c - 为在C中转换为字符串的int数组动态分配内存

c - 在 C 中使用结构的段错误

c - malloc 未使用指向指针的指针正确分配

c - 具有函数 c 的动态矩阵

c++ - c 在这两种情况下如何工作以及有什么区别

objective-c - 如何从看不到 Obj-C 变量的 C 函数中写入 NSObject?

c - 安排代码以分隔 C 中的函数

c - 如何在 C 中的字符串中找到字符的索引?

c - 我正在尝试制作二维数组,将其传递给函数,然后在 main 中更新修改后的数组

c - C 中 malloc 分配的意外大小输出