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