c - 如何修复 "Segmentation fault(core dumped)"?

标签 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] 时,您正在读取未初始化的内存,因为您从未像 Ry- 中提到的那样初始化过 b评论。

关于c - 如何修复 "Segmentation fault(core dumped)"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58511141/

相关文章:

c++ - 函数指针中的参数列表

子进程需要seteuid为root,父进程不需要

c - 向 printf() 添加换行符会更改代码行为

c - 在 C 中递增指针数组

c - 读入特定数量的变量

c++ - 编译成更快的代码 : "n * 3" or "n+(n*2)"?

c - 列出对我的库的所有调用

android - strerror(errno) 调用 read() 和 write() 时返回 "Invalid argument"

c - 在 C 中使用链表

c - 将 C 字符串转换为所有一种情况处理器的最快方法