首页 > 解决方案 > 如何修复“分段错误(核心转储)”?

问题描述

我正在尝试执行这段代码,编译部分没问题,前半部分也没问题。我没有看到我试图访问未分配给数组的内存的位置

#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;
}

标签: c

解决方案


您的变量ind可以增长很多100,因此(对于,a[ind]类似)可能是越界访问。bc

当你a[i] == b[j]在你的代码中写代码时,你正在读取未初始化的内存,因为你从未b在注释中初始化为 Ry-提及。


推荐阅读