a value indicating that a pointer does not refer to a valid object
In computing, a null pointer (sometimes shortened to nullptr or null) or null reference is a value indicating that the pointer or reference does not refer to an object. Programs routinely use โ€ฆ Wikipedia
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Null_pointer
Null pointer - Wikipedia
June 13, 2026 - In practice, dereferencing a null pointer may result in an attempted read or write from memory that is not mapped, triggering a segmentation fault or memory access violation. This may manifest itself as a program crash, or be transformed into a software exception that can be caught by program code. There are, however, certain circumstances where this is not the case. For example...
Discussions

java - Null pointer access: The variable data can only be null at this location - Stack Overflow
You are initializing the array data to be null, when you try to access it it gives you null pointer access error. More on stackoverflow.com
๐ŸŒ stackoverflow.com
c++ - Accessing null pointer causes seg fault - Stack Overflow
If it's really the if condition itself causing the segfault, that means the value of this inside iterateFoos() is invalid - perhaps you're dereferencing a null/dangling pointer when calling it. More on stackoverflow.com
๐ŸŒ stackoverflow.com
c++ - Attempting to access a null pointer - Stack Overflow
Windows will give you an "Access violation", Linux/Unix will give you a "segmentation fault". Also, see Why are NULL pointers defined differently in C and C++? for a quote of what a null pointer is in the standard More on stackoverflow.com
๐ŸŒ stackoverflow.com
What is the difference between Null Pointer exception and Core Dump (Segmentation fault) in C/C++?
The C++ Standard doesn't care. From Section 3.27: Undefined behavior may be expected when this document omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data. The dereferencing operators * and -> are only defined for the first type of pointer in the standard - a pointer to an object or function. Everything else is undefined, and is up to how the compiler and runtime environment are implemented. That way lies dragons. On my system: Linux doesn't care, either. Either the process is allowed to access a particular address in memory, or it isn't. If I dereference the null pointer, I get a segfault, just like if I try to dereference a pointer containing 0xdeadbeef. Null isn't special other than that the OS will never allow you to access memory with that address and that it's frequently used as a pointer value that signifies nonexistence. More on reddit.com
๐ŸŒ r/learnprogramming
13
2
August 13, 2020
Top answer
1 of 12
4227

There are two overarching types of variables in Java:

  1. Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives.

  2. References: variables that contain the memory address of an Object i.e. variables that refer to an Object. If you want to manipulate the Object that a reference variable refers to you must dereference it. Dereferencing usually entails using . to access a method or field, or using [ to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type Object are references.

Consider the following code where you declare a variable of primitive type int and don't initialize it:

int x;
int y = x + x;

These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. All primitives have to be initialized to a usable value before they are manipulated.

Now here is where things get interesting. Reference variables can be set to null which means "I am referencing nothing". You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null).

If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException.

The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.

Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null.

In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer object.

If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.

For instance, you may have a method as follows:

public void doSomething(SomeObject obj) {
   // Do something to obj, assumes obj is not null
   obj.myMethod();
}

In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:

doSomething(null);

In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.

If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.

In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:

// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");

Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:

/**
  * @param obj An optional foo for ____. May be null, in which case
  *  the result will be ____.
  */
public void doSomething(SomeObject obj) {
    if(obj == null) {
       // Do something
    } else {
       // Do something else
    }
}

Finally, How to pinpoint the exception & cause using Stack Trace

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?

Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically

Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.

In Java 14, the following is a sample NullPointerException Exception message:

in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null

List of situations that cause a NullPointerException to occur

Here are all the situations in which a NullPointerException occurs, that are directly* mentioned by the Java Language Specification:

  • Accessing (i.e. getting or setting) an instance field of a null reference. (static fields don't count!)
  • Calling an instance method of a null reference. (static methods don't count!)
  • throw null;
  • Accessing elements of a null array.
  • Synchronising on null - synchronized (someNullReference) { ... }
  • Any integer/floating point operator can throw a NullPointerException if one of its operands is a boxed null reference
  • An unboxing conversion throws a NullPointerException if the boxed value is null.
  • Calling super on a null reference throws a NullPointerException. If you are confused, this is talking about qualified superclass constructor invocations:
class Outer {
    class Inner {}
}
class ChildOfInner extends Outer.Inner {
    ChildOfInner(Outer o) { 
        o.super(); // if o is null, NPE gets thrown
    }
}
  • Using a for (element : iterable) loop to loop through a null collection/array.

  • switch (foo) { ... } (whether its an expression or statement) can throw a NullPointerException when foo is null.

  • foo.new SomeInnerClass() throws a NullPointerException when foo is null.

  • Method references of the form name1::name2 or primaryExpression::name throws a NullPointerException when evaluated when name1 or primaryExpression evaluates to null.

    a note from the JLS here says that, someInstance.someStaticMethod() doesn't throw an NPE, because someStaticMethod is static, but someInstance::someStaticMethod still throw an NPE!

* Note that the JLS probably also says a lot about NPEs indirectly.

2 of 12
972

NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page.

Probably the quickest example code I could come up with to illustrate a NullPointerException would be:

public class Example {

    public static void main(String[] args) {
        Object obj = null;
        obj.hashCode();
    }

}

On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing.

(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)

๐ŸŒ
Quora
quora.com โ€บ What-happens-when-we-try-to-access-a-null-pointer-in-C
What happens when we try to access a null pointer in C? - Quora
Answer (1 of 4): The standard says that accessing a NULL ptr is โ€œundefined behaviorโ€. Undefined behavior can be anything, including: * Nothing at all - continue running the program as if nothing happened * Crashing the application * Corrupting application data From Wikipedia we have this: ...
๐ŸŒ
Udemy
blog.udemy.com โ€บ home โ€บ it & development โ€บ software development โ€บ java null pointer exception basics for beginners
Java Null Pointer Exception Basics for Beginners - Udemy Blog
April 14, 2026 - 1. Trying to call an instance of a null object and modifying or accessing fields with the Null object ยท 2. Passing Null to a function where real value of some kind of reference value is required ยท The summary of the above two scenarios is ...
๐ŸŒ
ScienceDirect
sciencedirect.com โ€บ topics โ€บ computer-science โ€บ null-pointer
Null Pointer - an overview | ScienceDirect Topics
We will begin with a simple example: a null pointer. In laymanโ€™s terms, a null pointer is a pointer to an address in the memory space that does not have a meaningful value and cannot be referenced by the calling program, for whatever reason. This will normally lead to an unhandled error, resulting in a segmentation fault...
Find elsewhere
๐ŸŒ
Quora
quora.com โ€บ What-is-a-NULL-pointer-exception-What-are-some-real-world-scenarios-where-we-can-encounter-one
What is a NULL pointer exception? What are some real-world scenarios where we can encounter one? - Quora
Some computer architectures have a protective fault/exception/interrupt for trying to use a NULL or zero address in a memory access, like dereferencing or jumping with an uninitialized pointer in C, for example.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-lang-nullpointerexception
Java NullPointerException - Detect, Fix, and Best Practices | DigitalOcean
August 3, 2022 - Technical tutorials, Q&A, events โ€” This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
๐ŸŒ
Rollbar
rollbar.com โ€บ home โ€บ how to catch and fix nullpointerexception in java
How to Catch and Fix NullPointerException in Java
June 30, 2026 - Your program does the same thing when it tries to access methods or properties of a null object, and it crashes as a result. The good news? NullPointerExceptions are highly preventable once you know what to look for. Some of the most common scenarios for a NullPointerException are: ... Here is an example of a NullPointerException thrown when the length() method of a null String object is called:
๐ŸŒ
Medium
medium.com โ€บ @geekpreet4u โ€บ understanding-null-pointer-exception-a-deep-dive-into-machine-code-stack-traces-and-cpu-d60bfaa092b1
Understanding Null Pointer Exception : A Deep Dive into Machine Code, Stack Traces, and CPU Mechanics | by Preethi Viswanathan | Medium
December 31, 2025 - section .data str dq 0 ; Null pointer section .text mov rax, [str] ; Load null pointer into RAX mov rbx, [rax+4] ; Dereference pointer (causes fault) This is an example of register addressing. It means the CPU is trying to access memory at an address that is 4 bytes ahead of the address stored in the EAX register.
๐ŸŒ
Dronatechnoworld
dronatechnoworld.com โ€บ 2023 โ€บ 01 โ€บ what-is-null-pointer-error-in-java-and.html
Technology World: What is Null Pointer Error in Java and How to fix it?
January 24, 2023 - There are several ways to fix a null pointer error, but the most common solution is to check for null values before trying to access an object. This can be done by using an if statement to check if the variable is null, and if so, assign a value to it or handle the error in a specific way. Another way is to use the "Optional" class introduced in Java 8, it allows to avoid null pointer exceptions. It can be used with any type of variable and it wraps the variable and it can check if it's present or not. For example, if the error occurs when trying to access an object called "objectName," the following code can be used to fix it:
Top answer
1 of 5
4
The C++ Standard doesn't care. From Section 3.27: Undefined behavior may be expected when this document omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data. The dereferencing operators * and -> are only defined for the first type of pointer in the standard - a pointer to an object or function. Everything else is undefined, and is up to how the compiler and runtime environment are implemented. That way lies dragons. On my system: Linux doesn't care, either. Either the process is allowed to access a particular address in memory, or it isn't. If I dereference the null pointer, I get a segfault, just like if I try to dereference a pointer containing 0xdeadbeef. Null isn't special other than that the OS will never allow you to access memory with that address and that it's frequently used as a pointer value that signifies nonexistence.
2 of 5
4
The difference is that NullPointerExceptions come from managed languages which actually check if you're dereferencing NULL, whereas a segfault is the OS telling you to go away and stop messing with memory you shouldn't be messing with. It's really a matter of how much abstraction there is between the language and the underlying architecture (i.e. how low/high level the language is). In a language like Java you can basically imagine every method call/field access looks like this C++ code (and it shares the associated performance cost!): if (!obj) throw NullPointerException(blahblah); obj->method();
Top answer
1 of 5
76

Short answer: it depends on a lot of factors, including the compiler, processor architecture, specific processor model, and the OS, among others.

Long answer (x86 and x86-64): Let's go down to the lowest level: the CPU. On x86 and x86-64, that code will typically compile into an instruction or instruction sequence like this:

movl $10, 0x00000000

Which says to "store the constant integer 10 at virtual memory address 0". The Intelยฎ 64 and IA-32 Architectures Software Developer Manuals describe in detail what happens when this instruction gets executed, so I'm going to summarize it for you.

The CPU can operate in several different modes, several of which are for backwards compatibility with much older CPUs. Modern operating systems run user-level code in a mode called protected mode, which uses paging to convert virtual addresses into physical addresses.

For each process, the OS keeps a page table which dictates how the addresses are mapped. The page table is stored in memory in a specific format (and protected so that they can not be modified by the user code) that the CPU understands. For every memory access that happens, the CPU translates it according to the page table. If the translation succeeds, it performs the corresponding read/write to the physical memory location.

The interesting things happen when the address translation fails. Not all addresses are valid, and if any memory access generates an invalid address, the processor raises a page fault exception. This triggers a transition from user mode (aka current privilege level (CPL) 3 on x86/x86-64) into kernel mode (aka CPL 0) to a specific location in the kernel's code, as defined by the interrupt descriptor table (IDT).

The kernel regains control and, based on the information from the exception and the process's page table, figures out what happened. In this case, it realizes that the user-level process accessed an invalid memory location, and then it reacts accordingly. On Windows, it will invoke structured exception handling to allow the user code to handle the exception. On POSIX systems, the OS will deliver a SIGSEGV signal to the process.

In other cases, the OS will handle the page fault internally and restart the process from its current location as if nothing happened. For example, guard pages are placed at the bottom of the stack to allow the stack to grow on demand up to a limit, instead of preallocating a large amount of memory for the stack. Similar mechanisms are used for achieving copy-on-write memory.

In modern OSes, the page tables are usually set up to make the address 0 an invalid virtual address. But sometimes it's possible to change that, e.g. on Linux by writing 0 to the pseudofile /proc/sys/vm/mmap_min_addr, after which it's possible to use mmap(2) to map the virtual address 0. In that case, dereferencing a null pointer would not cause a page fault.

The above discussion is all about what happens when the original code is running in user space. But this could also happen inside the kernel. The kernel can (and is certainly much more likely than user code to) map the virtual address 0, so such a memory access would be normal. But if it's not mapped, then what happens then is largely similar: the CPU raises a page fault error which traps into a predefined point at the kernel, the kernel examines what happened, and reacts accordingly. If the kernel can't recover from the exception, it will typically panic in some fashion (kernel panic, kernel oops, or a BSOD on Windows, e.g.) by printing out some debug information to the console or serial port and then halting.

See also Much ado about NULL: Exploiting a kernel NULL dereference for an example of how an attacker could exploit a null pointer dereference bug from inside the kernel in order to gain root privileges on a Linux machine.

2 of 5
6

As a side note, just to compel the differences in architectures, a certain OS developed and maintained by a company known for their three-letter acronym name and often referred to as a large primary color has a most-fasicnating NULL determination.

They utilize a 128-bit linear address space for ALL data (memory AND disk) in one giant "thing". In accordance with their OS, a "valid" pointer must be placed on a 128-bit boundary within that address space. This, btw, causes fascinating side effects for structs, packed or not, that house pointers. Anyway, tucked away in a per-process dedicated page is a bitmap that assigns one bit for every valid location in a process address space where a valid pointer can lay. ALL opcodes on their hardware and OS that can generate and return a valid memory address and assign it to a pointer will set the bit that represents the memory address where that pointer (the target pointer) is located.

So why should anyone care? For this simple reason:

int a = 0;
int *p = &a;
int *q = p-1;

if (p)
{
// p is valid, p's bit is lit, this code will run.
}

if (q)
{
   // the address stored in q is not valid. q's bit is not lit. this will NOT run.
}

What is truly interesting is this.

if (p == NULL)
{
   // p is valid. this will NOT run.
}

if (q == NULL)
{
   // q is not valid, and therefore treated as NULL, this WILL run.
}

if (!p)
{
   // same as before. p is valid, therefore this won't run
}

if (!q)
{
   // same as before, q is NOT valid, therefore this WILL run.
}

Its something you have to see to believe. I can't even imagine the housekeeping done to maintain that bit map, especially when copying pointer values or freeing dynamic memory.

Top answer
1 of 1
1

As far as I can see you never initialise your pointer.

You declare Splav *sp but never create a new Splav instance which means trying to call a method later is undefined behaviour. So you would need to pass in a Splav pointer into the constructor, or construct a new pointer inside it, however....

The bigger problem is that in Splav you have a pointer to Prikazi and in Prikazi you have a pointer to Splav. This is a circular dependency - you need a Splav to create a Prikazi but you need a Prikazi to create a Splav. This is a bad situation to be in, essentially having a chicken & egg situation.

#include "Prikazi.h"

class Prikazi;

You don't need to forward-declare if you are already including the header. Forward-declaring is essentially promising the compiler that there will be a class when it needs it, but not right now.

You need to ask yourself if these two classes really need to know about each other before coupling them so closely. For example in Splav all you really seem to do is take the width and height from Prikazi and store them internally - that in itself is a bit questionable but if you need to do it then just pass in two integers in the constructor. Then you need to instantiate a Splav item and pass it into Prikazi and store it in the sp variable.

Overall, your problem is stemming from poor design and I would really recommend picking up a book (or watch a tutorial) on the very basics of c++ programming. A tip for the future is to write all your code in English, makes it much easier to follow along which helps when you need to ask questions. Also upon reaching this point I realise we're in the gamedev section and this isn't really related to game programming but really the basics of programming - but I already typed it out so there we go.

๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 632285 โ€บ java โ€บ null-pointer-access-variable-null
null pointer access the variable can only be null at this location (Beginning Java forum at Coderanch)
April 16, 2014 - Michelle Ruth wrote:I'm getting an error on line 137 and all it is If that's the line that's causing the exception then the rs variable is null. To fix it you have to ensure the rs variable is not null.