Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which case the C++ this pointer can be NULL

I experienced an issue that in the class constructor while I was using this pointer, but this pointer happen to be NULL at that time. for example

MyClass::MyClass()
{
   //this pointer happen to be NULL in this case, and it crash in teh m_callbackfunc because it does not handle null input.
   m_callbackFunc(this);
}

I wonder why this pointer can be null? and in which case this pointer can be null?

like image 714
user454083 Avatar asked Jul 10 '15 08:07

user454083


People also ask

When can this pointer be null?

A null pointer is a pointer which points nothing. Some uses of the null pointer are: a) To initialize a pointer variable when that pointer variable isn't assigned any valid memory address yet. b) To pass a null pointer to a function argument when we don't want to pass any valid memory address.

What are null pointers in C?

A Null Pointer is a pointer that does not point to any memory location. It stores the base address of the segment. The null pointer basically stores the Null value while void is the type of the pointer. A null pointer is a special reserved value which is defined in a stddef header file.

Why would a pointer be null?

A null pointer has a reserved value that is called a null pointer constant for indicating that the pointer does not point to any valid object or function. You can use null pointers in the following cases: Initialize pointers. Represent conditions such as the end of a list of unknown length.

How do you set a pointer to null?

In C programming language a Null pointer is a pointer which is a variable with the value assigned as zero or having an address pointing to nothing. So we use keyword NULL to assign a variable to be a null pointer in C it is predefined macro.


1 Answers

The only way a this pointer can be NULL is if some code in the program has exhibited undefined behaviour.

It might for example be achieved by something like

  void *place = nullptr;
  MyClass *object = new (place) MyClass();

The problem is that this effectively dereferences a NULL pointer, so has undefined behaviour. So it is possible that MyClass constructor will have this as NULL. Any other effect is also possible - such is the nature of undefined behaviour.

Some debuggers also report this to be a NULL pointer. But that isn't actually a sign of this being NULL. It is a sign that this is a language keyword rather than something with a symbolic name in object files that the debugger can find. Some other debuggers, when asked to evaluate this simply report that nothing with that name exists in the current function/scope/whatever - possibly because the C++ compiler implements this by passing a value in a machine register.

like image 97
Peter Avatar answered Sep 24 '22 03:09

Peter