1

背景:我试图澄清 C 中指针和动态内存分配的奥秘。我试图从用户那里获取几个浮点输入,将它们存储在一个动态分配的数组中,从而扩展以容纳更多值。一旦用户输入 0,循环终止,计算和打印总和和平均值。我正在使用 Borland C 5.02

问题: 1.循环只工作了4次,然后第4个值没有存储!
2. 如果我将 x+i 替换为 x[i] 并将 *(x+i-1) 替换为 x[i-1] 我得到“浮点错误:堆栈错误”“程序异常终止。

int main(void)
{
   float *x;
   float sum=0;
   float avg=0;
   int i=0;

   x=(float*)malloc(sizeof(float));

   do
   {
        scanf("%f",x+i);  //take input

      i++;
      x=(float*)realloc(x, i*sizeof(float));  //reallocate memory to store more values
      if(x==NULL){printf("WARNING");}

      printf("\n%f    %p   %d\n",*(x+i-1),x,i);

   }while(*(x+i-1)!=0);

   for(int j=0;j<i;j++)
   {sum=sum+*(x+j);} // Sum all values

   avg=sum/(i-1);   //Find result, i is 1 bigger than number of values, ith value is 0

   printf("\n\n%d   sum: %f   avg: %f ",i,sum,avg);
   getch();
   return 0;
}
4

2 回答 2

10

由于i是基于 0 的,因此您的 realloc 应该是: x=(float*)realloc(x, (i+1)*sizeof(float));

于 2012-06-29T04:24:11.993 回答
0

I compiled your program and ran it. I built with -g and tried debugging it. It gives this message and then a stack backtrace:

*** glibc detected *** ./a.out: realloc(): invalid next size: 0x0000000000797010 ***

For me, it dies after the 6th number.

I did a search on the above error message about "invalid next size" and haven't found anything really useful. All the answers I found are basically "you did something that corrupted your heap" but in your program I don't spot anything that should be doing that.

EDIT: Okay, sure enough, it was heap corruption caused by writing after the end of the allocated memory. That should teach me. There was one call to realloc() and one place that was writing to the memory; the bug had to be one of those two lines!

于 2012-06-29T04:38:54.833 回答