简体   繁体   English

实现插入排序时出现分段错误

[英]Segmentation fault when implementing insertion sort

#include <iostream>

using namespace std;

int main(){
    int a[6] = {5, 2, 4, 6, 1, 3}; // create an array of size 6
    int j, key = 0;
    for (int i = 1; i < 6; i++) {
        key = a[i];
        j = i - 1;
        while ((j >= 0) && (a[j] > key)) {
            a[j + 1] = a[j];
            j -= 1;
        }
        a[j + 1] = key;
    }
    for (int l = 0; l < 6; l++) { 
        cout << a[l];
    }
    return 0;
}

I'm trying to test my insertion sort code using an array the code complies but when I try to execute the a.out file, it gives me "Segmentation Fault", I look up what segmentation fault is, it's basically an error that we are trying to access the forbidden memory location, however, I'm wondering where exactly is the error in my code. 我正在尝试使用代码符合条件的数组来测试我的插入排序代码,但是当我尝试执行a.out文件时,它给了我“ Segmentation Fault”,我查明了细分错误是什么,从本质上讲,这是一个错误正在尝试访问禁止的内存位置,但是, 我想知道代码中的错误到底在哪里。 Also, if i get rid of the 另外,如果我摆脱了

for (int l = 0; l < 6; l++) { 
    cout << a[l];
}

no error is found. 找不到错误。

Your variable j is not initialized and so may be anything when you first access a[j] . 变量j未初始化,因此在您首次访问a[j]时可以是任何东西。 That causes the segmentation fault. 这会导致分段错误。 ( int j,key =0; only sets key to 0 but not j .) int j,key =0;仅将key设置为0 ,而不将j设置为。)

Always compile your code with -Wall , this would have told you about the use of the uninitialized variable. 始终使用-Wall编译代码,这将告诉您未初始化变量的用法。 (Correction: My gcc 4.7 doesn't catch it. How lame.) (更正:我的gcc 4.7无法捕获它。真是la脚。)

(The reason why the error goes away when you remove the printing is that you have compiler optimizations turned on: The compiler then notices that you never do anything practical with the computed values and arrays and just throws everything into the bin and gives you an empty program.) (删除打印件后错误消失的原因是您启用了编译器优化:编译器随后注意到,您永远不会对计算值和数组进行任何实际操作,只会将所有内容都丢到bin中并为您提供空白程序。)

sorting is one of the algorithms in the stl. 排序是stl中的算法之一。 you should really be using std::sort like 你真的应该使用std :: sort之类的

std::sort( a, a+6 );

PS: j is initialized before use in the line PS:j在行中使用之前已初始化

j = i - 1;

so that is not the cause of the crash. 因此这不是崩溃的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM