【问题标题】:Malloc fails when the input size exceeds 10输入大小超过 10 时 malloc 失败
【发布时间】:2021-05-08 04:37:42
【问题描述】:

我正在使用 malloc 分配内存,但是当输入大小超过 10 时失败,为什么会发生这种情况?

我也给出了代码和错误信息:

错误信息

解决方案:malloc.c:2385: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' 失败。

代码

int birthdayCakeCandles(int candles_count, int* candles) {

 int temp,i,flag=1;
for (i=1;i<=candles_count;i++){
  if(candles[0]<candles[i]) {
      temp=candles[0];
      candles[0]=candles[i];
      candles[i]=temp;
  }
 else if(candles[0]==candles[i]){
      flag=flag+1;
  }
}
return flag;
}

int main()
{   int candles_count,i;
scanf("%d",&candles_count);
   int *candles= (int*)malloc(candles_count*sizeof(int));
   for(i=0;i<candles_count;i++){
     scanf("%d",(candles+i));  
   }

    int result = birthdayCakeCandles(candles_count, candles);
    printf("%d",result);
    free(candles);
    return 0;
}

【问题讨论】:

  • for (i=1;i&lt;=candles_count;i++) 溢出缓冲区。在最后一次迭代中,i 的值 candles_count 不是数组的有效索引。看起来应该是for (i=1;i&lt;candles_count;i++)
  • 感谢它真正起作用的帮助!发生这种情况是因为我使用了一个不指向内存位置的“i”值吗?
  • 欢迎来到 SO。你的问题没有写清楚。请阅读stackoverflow.com/help/how-to-ask

标签: c malloc dynamic-arrays


【解决方案1】:

在第 4 行中,您从索引 1 开始,一直检查到索引 N(

【讨论】:

    猜你喜欢
    • 2013-01-11
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多