首页 > 解决方案 > 如何避免插入排序中的 SIGSEGV 错误

问题描述

我正在尝试在 C 中实现插入排序算法。但我得到的只是在线 IDE 中的SIGSEGV 错误,并且输出未显示在Code::Blocks中。如何避免此类错误。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    /* Here i and j are for loop counters, temp for swapping
       count  for total number of elements,array for elements*/

    int i, j, temp, count;
    printf("How many numbers are you going to enter");
    scanf("%d", &count);
    int n[20];
    printf("Enter %d elements", count);

    // storing elements in the array
    for(i = 0; i < count; i++) {
        scanf("%d", n[i]);
    }

    // Implementation of insertion sort algorithm
    for(i = 0; i < count; i++) {
        temp = n[i];
        j = i - 1;

        while(temp < n[j]) {
            n[j+1] = n[j];
            j = j - 1;
        }
        n[j+1] = temp;
    }

    printf("Order of sorted elements");
    for(i = 0; i < count; i++) {
        printf("%d", n[i]);
    }

    return 0;
}

标签: cruntime-errorinsertion-sort

解决方案


您的代码有几个问题。首先,什么是 SIGSEGV 错误?好吧,它是good old Segmentation faulterror 的别称,基本上就是你在访问无效内存(即不允许访问的内存)时遇到的错误。

  1. tl;博士:更改scanf("%d",n[i]);scanf("%d",&n[i]);。您正在尝试使用 读取初始值scanf("%d",n[i]);,这会引发分段错误错误,因为scanf需要将读取的值放入其中的地址,但您真正要做的是传递 的n[i]就好像它是一个地址一样(它不是,因为,由于您尚未为其设置任何值,因此它几乎只是内存垃圾)。更多关于这里

  2. tl;博士:更改int n[20];int n[count]。您的数组声明int n[20];将最多存储 20 个整数,如果有人想插入 21 个或更多值会怎样?您的程序保留了一定的堆栈(内存)空间,如果您超过该空间,那么您将偶然发现另一个程序的空间,并且警察(内核)会逮捕您(分段错误)。提示:尝试插入 21 和 100 值,看看会发生什么。

  3. tl;博士:更改for(i = 0; i < count; i++) {for(i = 1; i <= count; i++) {。这是您的索引的逻辑问题,您从开始i = 0并一直持续到i = count - 1在大多数数组迭代情况下都是正确的,但是由于j之前假设索引的值i,您需要i1( 所以j0,否则j = -1在第一次迭代 (不是有效的索引))。

我的最终代码如下。希望它有所帮助,快乐编码!

#include <stdio.h>
#include <stdlib.h>

int main() {
    /*Here i and j are for loop counters,temp for swapping
    count  for total number of elements,array for elements*/
    int i, j, temp, count;
    printf("How many numbers are you going to enter?\n");
    scanf("%d",&count);
    int n[count];
    printf("Enter %d elements\n",count);
    //storing elements in the array
    for(i = 0; i < count; i++) {
        scanf("%d", &n[i]);
    }
    //Implementation of insertion sort algorithm
    for(i = 1; i <= count; i++) {
        temp = n[i];
        j = i-1;
        while(temp < n[j]) {
            n[j+1] = n[j];
            j--;
        }
        n[j+1] = temp;
     }
     printf("Order of sorted elements\n");
     for(i = 0; i < count; i++) {
        printf("%d\n",n[i]);
     }
    return 0;
}

编辑:如果您在使用在线 IDE 时遇到问题,请考虑在本地运行程序,这样可以节省大量时间,此外:您永远不知道在线 IDE 使用什么内核版本或魔法来运行您的代码(相信我,当您'正在用 C 编码——相当低级的语言,这些东西有时会有所不同)。我喜欢使用所有根样式Vim作为文本编辑器以及gcc用于编译和gdb调试。


推荐阅读