Search code examples
c++gdbexecutionsegmentation-fault

SIGSEGV: Program doesn't execute sequentially


My program receives a SIGSEGV and I am trying to debug. 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.

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:

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.


Solution

  • 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.

    This is happening because you have an uninitialized pointer strinput, and you write to the unpredictable location where that pointer points to.

    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.