malloc (): повреждение памяти;Прервано (ядро сброшено) - PullRequest
0 голосов
/ 01 октября 2019

У меня серьезная проблема с командой malloc (). Дело в том, что я пишу код для вычисления остатка матричной линейной задачи. Для этого я выделяю память для хранения матричного вектора c, который сначала будет содержать результат умножения матрицы на вектор. После этого я просто вычитаю результирующий вектор другим вектором, вычисляю норму и т. Д. *

Ошибка возникает непосредственно при выделении после компиляции и дает

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.

1 Ответ

0 голосов
/ 01 октября 2019

Как советовали в комментариях, экземпляр valgrind позволил мне обнаружить, что проблема кроется в другом месте и действительно была из-за записи в конце выделения памяти.

Спасибо всем запомощь.

...