c - 输入大小超过 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;
}
解决方案
在第 4 行中,您从索引 1 开始,一直检查到索引 N(<= 符号),其中 N 是非索引项,并且您正在从不允许的区域读取内存。
推荐阅读
- ios - PFUser.become 返回无效的会话令牌
- php - laravel 新项目命令使用 php@7.3 代替 php@7.4
- jquery - 在媒体屏幕上显示 Jquery Slick 选项
- python - 按数字切片 Python 列表
- python-3.x - Python根据值的右子字符串从Dataframe中删除行
- python - 从 Selenium WebElement 中提取文本
- winapi - D3D11如何将纹理中alpha值为0的像素渲染为透明?
- javascript - 谷歌页面没有出现在我的电子应用程序中
- typescript - 如何将类型谓词分配给变量
- c# - WPF - 使用 ViewModel 更改标签内容