gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:00:43 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com