Two different memory errors depending on where I allocate the memory

时间:2015-07-28 15:46:42

标签: c memory-management

For my C program I have tried to allocate memory for a double array(ssi) which I then access in another function (spslicer). If I allocate this memory before I call a different function (kpmdos) which should be unrelated I get the error:

*** glibc detected *** ./SpecSli.ex: double free or corruption (!prev): 0x0000000000a86e40 ***

and if I allocate it after I get the error:

malloc.c:3830: _int_malloc: Assertion `(unsigned long)(size) >= (unsigned long)(nb)' failed.

Based on this I think that I did something wrong in kpmdos when I allocated the memory but I cannot see anything wrong:

void kpmdos(csptr A, int Mdeg, double nvec, double ctr, double wid, int n, double *mu){

  // initialize variables
  double *w = malloc(n*sizeof(double));
  //free(w);
  fill_rand(n, w);
  double *v = malloc(n*sizeof(double));
  divide_array(w, norm(w, n), v, n);

  double *vkm1 = malloc(n*sizeof(double)); 
  fill(n, 0, vkm1);
  double *vk = malloc(n*sizeof(double));
  memcpy(vk,v, n*sizeof(double));
  double *temp = malloc(n*sizeof(double));
  double *vkp1 = malloc(n*sizeof(double));
  double thet = pi/(Mdeg+1);
  double a1 = 1/(Mdeg+2.0);
  double a2 = sin(thet);
  double jac;
  double scal;

Then I do some other coding with no memory allocation.

  free(w);
  free(vkp1);
  free(vkm1);
  free(temp);
  free(vk);
  free(v);
}

The output using valgrind when it is allocated before the function is:

> > ==7045== HEAP SUMMARY:
> ==7045==     in use at exit: 46,452 bytes in 235 blocks
> ==7045==   total heap usage: 351 allocs, 116 frees, 66,700 bytes allocated
> ==7045== 
> ==7045== LEAK SUMMARY:
> ==7045==    definitely lost: 22,331 bytes in 146 blocks
> ==7045==    indirectly lost: 0 bytes in 0 blocks
> ==7045==      possibly lost: 0 bytes in 0 blocks
> ==7045==    still reachable: 24,121 bytes in 89 blocks
> ==7045==         suppressed: 0 bytes in 0 blocks
> ==7045== Rerun with --leak-check=full to see details of leaked memory
> ==7045== 
> ==7045== For counts of detected and suppressed errors, rerun with: -v
> ==7045== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

Please let me know if you know the problem or if you need more information.

1 个答案:

答案 0 :(得分:0)

谢谢大家的帮助。我终于找到了大部分内容。在我没有发布的编码期间,我有一个函数可以将数组中的所有变量更改为不同的函数,对于此函数,我输入了错误的数组大小。