计算内存块中所有数字的总和以及数组中所有元素的总和

Olb*_*a12 0 c pointers

在编译下面的程序时,终端给我以下消息"double free or corruption(out)".我想创建一个程序,首先计算数组中所有元素的总和,见下面的x.然后我想计算指针指向的内存块中所有数字的总和,见下面的y.我认为问题在于作业"y = x;"

int main(void)
{
    double x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    printf("The sum is %f\n", sum(x, 10));

    double *y = malloc(sizeof(double)*10);
    y = x;

    printf("The sum is %f\n", sum(y, 10));
    free(y);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Iha*_*imi 5

分配y = x覆盖malloc()编辑指针和你最终free()荷兰国际集团堆栈变量1未定义的行为.而且,malloc()永远不会free()编辑ed指针.

从你的代码,似乎你并不需要malloc()在所有2.但如果需要,那么这可能就是你所需要的

double *y;
y = malloc(10 * sizeof(*y));
if (y == NULL)
    return -1;
for (int i = 0 ; i < 10 ; ++i)
    y[i] = i + 1;
printf("The sum is %f\n", sum(y, 10));
free(y);
Run Code Online (Sandbox Code Playgroud)

1 你实际上free()是地址x.

2 你可以打电话sum(x, 10).