c - 如何修复“分段错误(核心转储)”?
问题描述
我正在尝试执行这段代码,编译部分没问题,前半部分也没问题。我没有看到我试图访问未分配给数组的内存的位置
#include <stdio.h>
int main(void){
int a[100], b[100], c[100], cont = 0, ind = 0, temp;
printf("Insert a integer number\n");
do{
printf("X = ");
scanf("%d", &temp);
if(temp >= 0)
a[cont] = temp;
cont++;
}
while(cont < 100 && temp > 0);
for(int i = 0; i < 100; i++){
for(int j = 0; j < 100; j++){
if(a[i] == b[j])
c[ind]++;
else{
b[ind] = a[i];
c[ind] = 1;
ind++;
}
}
}
printf("Exist %d different number in the list", ind);
for(int i = 0; i <= ind; i++){
printf("Number %d appears %d times", b[i], c[i]);
}
return 0;
}
解决方案
您的变量ind
可以增长很多100
,因此(对于,a[ind]
类似)可能是越界访问。b
c
当你a[i] == b[j]
在你的代码中写代码时,你正在读取未初始化的内存,因为你从未b
在注释中初始化为 Ry-提及。
推荐阅读
- javascript - 如何突出显示所有 div 并为每个 div 添加一种导航
- node.js - 如何修复更新与nodeJS中发送的ID不同的ID的PUT路由
- android - 如何解决在 setContentView() 之后返回 Null 的 findViewByID()
- python - 自动分配给 Python 默认参数的参数
- php - 如何实时更新页面以响应数据库更改?
- php - 如何让php将变量发送到python?
- laravel - 如何在Laravel 上使用 GuzzleHttp 提取标签
- java - 无法导入 android.support.v4.content.ContextCompat
- python - 使用在 Droplet 上执行的 BeautifulSoup 脚本时出错
- python - Matplotlib:如何根据列值为散点图圆圈赋予颜色