首页 > 解决方案 > 输入大小超过 10 时 malloc 失败

问题描述

我正在使用 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;
}

标签: cmallocdynamic-arrays

解决方案


在第 4 行中,您从索引 1 开始,一直检查到索引 N(<= 符号),其中 N 是非索引项,并且您正在从不允许的区域读取内存。


推荐阅读