Segmentation Fault


In the below code, i am getting segmentation fault at cout << ... Can anyone explain why it happens..... Any suggestion will be useful for me..... I am using MingW compiler in QT5.......





#include <iostream>
#include <strings.h>
using namespace std;

char ** ptr1, **ptr2;

char ** fun1()
{
char * ptr = "hello";
return &ptr;
}


int main()
{
ptr1 = fun1();

ptr2 = fun1();

cout << *ptr1;

cout << *ptr1; // I am getting segmentation fault here

return 0;
}
fun1 returns the address of a local variable which stops existing when fun1 returns. Dereferencing that pointer will result in undefined behavior.

Don't dereference dangling pointers.
Last edited on
Any function of the following form is incorrect:
1
2
3
4
5
6
T *f(/*...*/){
    //...
    T p;
    //...
    return &p;
}
In your case, T = 'char *'.

The problem is that the memory location that ptr1 points to has been overwritten because it resides at a stack position higher than the current stack frame. Such memory locations can be overwritten at any time by unknown code (the specific reasons for this are not important). When you do cout << *ptr1, you're passing a garbage pointer to a function that expects a pointer to a string, so the three most likely things that can happen are that either the pointer is completely invalid and the program crashes; the pointer is valid but points to random data, and the function is able to read some data before reaching invalid memory and crashing; or the pointer is valid and the data is not too invalid, and the function reads a few bytes of random garbage and returns to the caller.
Topic archived. No new replies allowed.