0

The code below works fine, but if I try to access the private member variable m_sal in the function fun(), it leads to segmentation fault.

Can any one explain what's the reason ?

class Emp
{
    int m_sal;
public :
    void fun(char* name)
    {
        std::cout<<"Name :"<<name<<std::endl;
    }
};

int main()
{
    Emp *e = NULL;
    e->fun("Hi");
    return 0;
}
dragosht
  • 3,237
  • 2
  • 23
  • 32
  • 1
    Because you have undefined behaviour. In both cases. And either (or any) result is possible when the behaviour is undefined. – eerorika Jul 24 '14 at 12:10
  • Calling function from NULL pointer ? I guess that's the reason for seg fault – Shumail Jul 24 '14 at 12:13
  • Possible duplicate: http://stackoverflow.com/questions/2474018/when-does-invoking-a-member-function-on-a-null-instance-result-in-undefined-beha – eerorika Jul 24 '14 at 12:20

4 Answers4

1

Calling a method by a NULL pointer - as you are doing - is undefined behaviour. So it may crash, not crash, do anything.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0

First might want to change your method's signature to read

void fun (const char* name) const;

Converting from "Hi" to char * is deprecated and const correctness highly recommended. Your crash is caused as people mentioned by calling your method on a null pointer. Try

Emp * e = new Emp;
e->fun("Hi");

instead.

dirkster
  • 522
  • 2
  • 5
0

Of course it crashes.

Emp *e = NULL;

creates a pointer which happens to be a null pointer (because of = NULL , but I am sure many of us would prefer = nullptr), so there is no memory allocated for the object it is pointing to. You need to create an object this pointer will point to:

Emp* e = new Emp;

and now you can use it.

The exact reason for the crash is that the application is trying to fetch a value from a very low memory address (pointer's value is 0, for some cases add a few padding bytes maybe for the correct memory layout of the C++ object, but highly possible in this case it just wants to read the memory at address 0) which in most cases and OS's is reserved to be used by the system.

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
0

In your code, e is a pointer, not an actual instance of an object. You can either have:

Emp e;
e.fun("Hi");
//No need to clean up stack variable

OR

Emp *e = new Emp;
e->fun("Hi");
delete e;   //don't forget to clean up!

What you have is undefined behavior because of using a null pointer to call a function.

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47