gpt4 book ai didi

c - 内存分配,C中的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:10:12 25 4
gpt4 key购买 nike

我有这个问题需要解决。我得到了一个程序,它应该分配内存来创建一个 double 组,但它出了点问题。基本上,main 和函数 create_array 坏了,我需要修复它。我想出的解决方案出现了段错误,我不确定为什么。

首先,我决定删除主 b/c 数组中的“free(array)”是一个指针,根据我的理解,它不存在于堆中。我尝试将函数“create_array”更改为以下内容

void create_array(double *x, unsigned long n) {

double *d = malloc((int)n *sizeof(double));

if(d == NULL){
printf("Sorry Memory Not Available. Program Terminated.\n");
exit(1);

}

x=d;
free(d);

}

这是我得到的:

int main(void) {
printf("\nProgram started...\n");
double *array = NULL;
int n = 20;
create_array(array, n);

if( array != NULL) {
populate_array(array, n);

// displays half of the values of the array
for(int i = 0; i < n/2; i++){
printf("%f\n", *array++);
}

// According to C standard, the program's behaviour, after the following
// call to the function free is considered "Undefined" and needs to be
// fixed.
free(array);
}

printf("Program terminated...\n");
return 0;
}

// THE FOLLOWING FUNCTION IS NOT PROPERLY DESINGED AND NEEDS TO BE FIXED
void create_array(double *x, unsigned long n) {
x = malloc(n *sizeof(double));
if(x == NULL){
printf("Sorry Memory Not Available. Program Terminated.\n");
exit(1);
}
}

void populate_array(double *array, int n) {
int i;
for(i = 0; i < n; i++)
array[i] = (i + 1) * 100;
}

当我运行我编辑的代码时,出现段错误。当我运行没有任何更改的代码时,它只是输出“程序已启动\n 程序已终止”。

最佳答案

问题是,在提供的代码和片段中,由 malloc 的返回值分配的变量一直存在,直到函数返回。所以你需要使用指针到指针。此外,在第一个片段中,如果您释放已经分配的区域,您将不能再使用该空间。

void create_array(double **x, unsigned long n) {
*x = malloc(n *sizeof(double));
if(*x == NULL){
printf("Sorry Memory Not Available. Program Terminated.\n");
exit(1);
}
}

在 main 中,您可以将其称为 create_array(&array, n);

关于c - 内存分配,C中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58621584/

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