gpt4 book ai didi

c - malloc() : memory corruption; Aborted (core dumped)

转载 作者:行者123 更新时间:2023-11-30 16:13:00 26 4
gpt4 key购买 nike

我在使用 malloc() 命令时遇到严重问题。事情是这样的:我正在编写代码来执行矩阵线性问题的残差计算。为此,我分配内存来存储矩阵 vector c,它将首先保存矩阵 vector 乘法的结果。然后,我只需用另一个 vector 减去所得 vector ,计算范数等...

编译后分配时发生错误并给出

malloc(): memory corruption
Aborted (core dumped)

我在这里提供代码

#include <stdlib.h>
#include <stdio.h>
#include "../headers/norm.h"
#include "../headers/prodMatVec.h"

double residual(int size, double *a, int *ja, int *ia, double *x, double *b)
/*
Aim
===

The following functions evaluates the residual of the resolution
of a linear problem of the form

Ax = b

As the output of the resolution of such a problem is the vector x,
the residual gives an indication on how far (in terms of the
the euclidian norm of vectors) lies the product Ax from what it
should exactly be, namely b. Therefore, the normalized residual is

||Ax - b||
r = ==========
||b||

This operation involves functions such as matrix-vector product
and the application of the euclidian norm. These are described
in the corresponding functions.

Arguments
=========
size (input) - size of the given vectors and matrix
x (input) - points to table 'x'
ia (input) - points to table 'ia' from matrix A
ja (input) - points to table 'ja' from matrix A
a (input) - points to table 'a' from matrix A
b (input) - points to table 'b'
*/
{

/* Variables declaration */
int i;
double *c, num, denom;

/* Memory allocation for temporary result of matrix-vector product */
c = malloc(size * sizeof(double)); // PROBLEM: MEMORY CORRUPTION
if (c == NULL) {
printf("\n ERROR : not enough memory to generate the system\n\n");
return 1;
}

/* Computation of matrix-vector product */
prodMatVec(size, a, ja, ia, x, c);

/* Computation of the numerator vector */
for(i = 0; i < size; i++)
c[i] -= b[i];

/* Computation of norms */
num = norm(size, c);
denom = norm(size, b);

for(i = 0; i < size; i++) // not necessary
c[i] = 1;

/* Memory release */
free(c);

/* Return the quotient between both terms */
return num/denom;
}

有人可以帮助我吗?如果需要,我可以提供更多信息。

提前致谢!

编辑:

使用gdb(我不熟悉)代码给出

malloc(): memory corruption

Thread 1 "main" received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
51 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.

最佳答案

正如评论中所建议的,valgrind 的一个实例让我发现问题出在其他地方,并且确实是由于内存分配结束时的写入所致。

感谢大家的帮助。

关于c - malloc() : memory corruption; Aborted (core dumped),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58191665/

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