Question

This is a quite basic question but I've been looking everywhere and couldn't find an answer.

Consider the following code:

myFunction(MyObject** obj) {...}

int main()
{
  MyObject *obj = NULL;
  myFunction(&obj);
}

What is the result of this?

Is &obj NULL? undefined? Does it segfault?

Was it helpful?

Solution

No, the &obj will not be NULL, it will be the memory address holding the "value of obj", the pointer to MyObject. It is as simple as

int x = 0;
int *ptrTox = &x;

In this case ptrTox will contain address of x, and not zero. It can be any valid address.

OTHER TIPS

A pointer is simply a variable that stores an address (with a constraint on the type of what lies at this address).

So while it stores an address, it also has its own address in memory.

In your case, &obj is the address of this variable, and is neither NULL nor undefined, and accessing it won't segfault (if you avoid performing operations with obj that need to access what's pointed at, obviously). Indeed, the variable obj is declared and defined in your code.

Your myFunction() is getting the address of the obj (as passing &obj). You have created a pointer of MyObject class named obj. So It should not be null. Which hold address of memory of obj pointer.

Segfault is described here What is a segmentation fault?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top