Srinivasa Lakkaraju
Srinivasa Lakkaraju

Reputation: 666

Accessing private member leading to seg fault

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;
}

Upvotes: 0

Views: 1669

Answers (4)

edtheprogrammerguy
edtheprogrammerguy

Reputation: 6039

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.

Upvotes: 0

Ferenc Deak
Ferenc Deak

Reputation: 35428

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.

Upvotes: 0

dirkster
dirkster

Reputation: 522

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.

Upvotes: 0

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

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

Upvotes: 1

Related Questions