简体   繁体   English

SIGSEGV:程序未按顺序执行

[英]SIGSEGV: Program doesn't execute sequentially

My program receives a SIGSEGV and I am trying to debug. 我的程序收到一个SIGSEGV,我正在尝试调试。 The strange thing is that when I use gdb to go line by line, the program is not following what I think should be the normal execution flow. 奇怪的是,当我使用gdb逐行执行时,程序没有按照我认为的正常执行流程进行操作。

This is my code: 这是我的代码:

#include <iostream>
#include <fstream>

using namespace std;

char * str_reverse(char * s);

int main (int argv, char ** argc){
    char * strinput;

    fstream finput;
    fstream foutput;

    finput.open(argc[1], ios::in);
    finput >> strinput;
    finput.close();

    foutput.open(argc[2], ios::out);
    foutput << str_reverse(strinput);
    foutput.close();

    return 1;
}

char * str_reverse(char * s){
    int len = 0;
    while (s[len] != '\000') len++;
    char * rev = new char[len];
    for (int i = 0; i < len; i++)
        rev[i] = s[len-(i+1)];
    rev[len] = '\000';  
    return rev;
}

This is what I see in gdb: 这是我在gdb中看到的内容:

18      foutput << str_reverse(strinput);
(gdb) n
19      foutput.close();
(gdb) n
21      return 1;
(gdb) n
11      fstream foutput;
(gdb) n
21      return 1;
(gdb) n

Program received signal SIGSEGV, Segmentation fault.

By the way, the program does what it is meant to do correctly: it opens a file, reads a string and saves it reversed in another file. 顺便说一句,该程序完成了正确的操作:打开一个文件,读取一个字符串,然后将其反向保存到另一个文件中。

the program is not following what I think should be the normal execution flow. 该程序没有遵循我认为应该是正常的执行流程。

I don't see any evidence of that. 我没有看到任何证据。 As far as I can see, your program is following the normal execution flow, then crashes after main returns. 据我所看到的,你的程序按照正常的执行流程, 经过崩溃main回报。

This is happening because you have an uninitialized pointer strinput , and you write to the unpredictable location where that pointer points to. 发生这种情况是因为您有一个未初始化的指针strinput ,并且您写入了该指针指向的不可预测的位置。

It so happens that in your execution environment that pointer points somewhere on stack, so you corrupt your stack, which then causes you to jump to a bad address, causing the crash. 碰巧在您的执行环境中,指针指向堆栈中的某个位置,因此您破坏了堆栈,然后导致您跳到错误的地址,从而导致崩溃。

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

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