I usually have an extension method like IsNullOrEmpty that wraps your first option and use it everywhere. Answer from Reasonable-Leg1830 on reddit.com
Top answer
1 of 6
30

In C and C++, pointers are inherently unsafe, that is, when you dereference a pointer, it is your own responsibility to make sure it points somewhere valid; this is part of what "manual memory management" is about (as opposed to the automatic memory management schemes implemented in languages like Java, PHP, or the .NET runtime, which won't allow you to create invalid references without considerable effort).

A common solution that catches many errors is to set all pointers that don't point to anything as NULL (or, in correct C++, 0), and checking for that before accessing the pointer. Specifically, it is common practice to initialize all pointers to NULL (unless you already have something to point them at when you declare them), and set them to NULL when you delete or free() them (unless they go out of scope immediately after that). Example (in C, but also valid C++):

void fill_foo(int* foo) {
    *foo = 23; // this will crash and burn if foo is NULL
}

A better version:

void fill_foo(int* foo) {
    if (!foo) { // this is the NULL check
        printf("This is wrong\n");
        return;
    }
    *foo = 23;
}

Without the null check, passing a NULL pointer into this function will cause a segfault, and there is nothing you can do - the OS will simply kill your process and maybe core-dump or pop up a crash report dialog. With the null check in place, you can perform proper error handling and recover gracefully - correct the problem yourself, abort the current operation, write a log entry, notify the user, whatever is appropriate.

2 of 6
8

The other answers pretty much covered your exact question. A null check is made to be sure that the pointer you received actually points to a valid instance of a type (objects, primitives, etc).

I'm going to add my own piece of advice here, though. Avoid null checks. :) Null checks (and other forms of Defensive Programming) clutter code up, and actually make it more error prone than other error-handling techniques.

My favorite technique when it comes to object pointers is to use the Null Object pattern. That means returning a (pointer - or even better, reference to an) empty array or list instead of null, or returning an empty string ("") instead of null, or even the string "0" (or something equivalent to "nothing" in the context) where you expect it to be parsed to an integer.

As a bonus, here's a little something you might not have known about the null pointer, which was (first formally) implemented by C.A.R. Hoare for the Algol W language in 1965.

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

Top answer
1 of 2
1

First of all you don't need double pointer. Initialization with NULL is important here. (Denotes the empty list).

SortedList *list = NULL;

This has the benefit that now if you want to make changes to it pass it's address.

func(&list);

And checking the empty list would be

   void func(SortedList **list){
      if( *list == NULL )
        /* empty */
   }

This is usually the way lists are implemented.


In your case you simply allocated to a local variable and instead of returning the memory address you have overwritten the pointer's value with NULL - there is memory leak in the code.

With your code it will be something like. Yes all that the initialization does is assigning it to NULL. This is one easy way out towards checking the NULL. At the very beginning making it NULL basically denotes that list is empty.(which is the case generally).

2 of 2
0

list is a pointer to a pointer. The actual list is in the value it points to, so you need to dereference it.

An empty list is just a null pointer, so you don't need to allocate anything in init().

void init(SortedList** list)
{
    *list=NULL;
    printf("%p\n", *list);
}
void isEmpty(SortedList** list)
{
    printf("%p\n", *list);
    if(*list == NULL) printf("List is empty\n");]
}

And in the main function, you don't need a double pointer, you use the & (address-of) operator to get the address of a pointer variable.

int main()  
{
    SortedList *list;
    init(&list);
    printf("Initialization with succes\n");
    isEmpty(&list);

    return 0;
}

You only really need double pointers for functions that modify the list. So you could use an ordinary pointer for isEmpty:

void isEmpty(SortedList* list)
{
    printf("%p\n", list);
    if(list == NULL) printf("List is empty\n");]
}

and then call it as:

isEmpty(list);

But it's probably simplest to be consistent across all your functions.

🌐
Dynamics Community
community.dynamics.com › forums › thread › details
How to check if list is empty string or null
How to check if list is empty · So if pass null or empty string to the list.. this if condition doesn't work, it still enters the if statement
🌐
Cplusplus
cplusplus.com › reference › list › list › empty
std::list::empty
Returns whether the list container is empty (i.e. whether its size is 0). This function does not modify the container in any way.
🌐
Stack Overflow
stackoverflow.com › questions › 34969717 › checking-if-a-linked-list-is-empty-in-c
Checking if a Linked list is Empty in C - Stack Overflow
However, the if statement never executes, even though the list is empty. The struct I'm given doesn't have a header node(I can't change it), so how would I go about fixing this? Any help would be much appreciated. ... By doing the malloc, your node is no longer NULL (assuming malloc succeeded to allocate the memory).
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 744707 › how-can-i-find-if-particular-index-in-a-list-is-em
How can I find if particular index in a list is Empty ? - Microsoft Q&A
For example if I consider the above table index[0] is empty as all three list have empty entries at 0 position ... An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
Find elsewhere
🌐
Quora
quora.com › What-is-the-best-way-to-check-if-a-linked-list-is-empty-or-not-in-C
What is the best way to check if a linked list is empty or not in C++? - Quora
Usually, you will use the Standard Template Library, where a linked list is implemented as std::list. In this case, you can just use the empty() method that returns true if the list is empty and false if it is not empt...
🌐
Quora
quora.com › How-can-you-check-if-a-linked-list-has-null-values-without-calling-its-size-function
How to check if a linked list has null values without calling its size() function - Quora
So it is a convenient way to signal ... a machine can understand? NULL is how. It is address 0x00000000, and is the long integer 0x00000000, but it is not used as a number or an address. It is “no address” , “no object” , “points to nothing”, “empty”, ...
Top answer
1 of 5
92

Generally, your lists should always be initialized. One common misconception is that queries can produce a null list, which is never true.

For example, consider the following code:

Account[] records = [SELECT Id, Name, AccountNumber FROM Account];
if(records!=null && !records.isEmpty()) {
    for(Account record: records) {
        // Do Something Here
    }
}

This is a waste of CPU time, because (a) records will never be null, and (b) iterating over an empty list is acceptable. Therefore, none of the three checks you might use are rarely appropriate. The only exception to this rule is when one query is used to fuel another query, in which case you would check for the presence of values before performing the query:

Account[] accounts = [SELECT Id, Name, AccountNumber FROM Account];
if(accounts.isEmpty()) {
    return;
}
Contact[] contacts = [SELECT Id, Name, Email FROM Contact WHERE AccountId IN :accounts];

For lists you create yourself, you should always initialize them before using them. This is true for other types, like sets and maps, as well. There are, however, times when you'll need to check for a specific condition before using some lists. It helps if you experiment with the various types to get a feel for when you should be aware that a list may be null.

For example, consider a variable that binds to a multi-select picklist:

public String[] selectedValues { get; set; }

In this case, selectedValues will either be null, or will not be empty. You only ever need to check for != null in this case. Part of becoming an efficient developer is recognizing the patterns in a system. If you're still using myVar != null && !myVar.isEmpty() as a condition, that generally means you're making one or even two checks too many.

There is always one correct condition to use in every situation. If this isn't true, that suggests that values were not properly initialized elsewhere.

Edit: Safe Navigation Operator

As a special exception, you can now use the Safe Navigation Operator to skip the null check. That looks like this:

if(records?.size() > 0) {
 /* Do something here */
}

Because of the changes brought in with the Safe Navigation Operator, when either size of the comparison is null, the result is false. If we want to abort early, then we can negate the entire thing:

if(!(records?.size() > 0)) {
  return;
}
2 of 5
14

It is generally best to avoid null values in code so using null list references to indicate empty lists isn't usually good approach. That is this code:

List<String> strings = new List<String>();
...
for (String item : strings) {
    ...
}

is clearer and safer than this code:

List<String> strings = null;
...
if (strings != null) {
    for (String item : strings) {
        ...
    }
}

So prefer empty lists to null list references.

Personally I find myList.size() > 0 to be clearer than !myList.isEmpty() because the latter amounts to "not is empty" which takes a moment to understand. But as people will use both forms get used to both.

🌐
UiPath Community
forum.uipath.com › help
How to validate Generic list is null or empty - Help - UiPath Community Forum
July 5, 2019 - Installer(.exe or .msi): License type(Free, Trial/License code):Free Studio/Robot version:2019.6.0 Current behavior: Error Message Value Cannot be Null Screenshot: i’m trying to read list of unread messages using outlook mail activity and storing the attachment names in List of Strings (lstattachment) , certain times mail may not have attachments that time when i try to read the lstattachment.Any() it throws error message Value cannot be null , how do i check lstattachment is null or empty , i h...
🌐
Medium
dipakgawade.medium.com › c-is-collection-empty-count-vs-any-1fc67ec2b0c9
C# — Is collection empty — Count vs Any? | by Dipak Gawade | Medium
December 21, 2020 - C# — Is collection empty — Count vs Any? Problem statement — Before operating on any collection, we check if the collection is null or empty. Null check is usually done by comparing with Null …
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 156691 › linked-lists-find-length-and-check-for-empty-list
Linked Lists: Find length and check for empty list - c++
For length, either compute it on demand in O(n) or keep a running count and update it in create/insert/delete for O(1) queries. The on-demand version is simplest and correct. int listCount(const nodeType* first) { int n = 0; for (const nodeType* cur = first; cur != NULL; cur = cur->link) ++n; return n; } bool emptyList(const nodeType* first) { return first == NULL; } A few correctness notes based on the code and replies: @Sci@phy is right that, if you choose to maintain a size, increment it in createList and insertBack, and decrement it in deleteFront (never in printList).
🌐
Stack Overflow
stackoverflow.com › questions › 46608656 › accessing-null-pointers-to-check-if-linked-list-is-empty-in-c
data structures - accessing null pointers to check if linked list is empty in C++ - Stack Overflow
Most of the times, in an empty list head is null, not it'snext. Look twice at the initalization and decide if you need to check head or it'snext for nullity.
🌐
Meziantou's blog
meziantou.net › checking-if-a-collection-is-empty-in-csharp.htm
Checking if a collection is empty in C# - Meziantou's blog
January 29, 2024 - In this post, I describe how to check if a collection is empty in C#, whatever the type of the collection
🌐
Beyondthecloud
blog.beyondthecloud.dev › blog › how-to-check-if-list-is-empty-in-apex
How to check if list is empty in Apex | Beyond The Cloud
February 27, 2025 - If we work with a code that we can’t control (e.g. consuming methods from the managed package, or maintained by another team where we can’t do the code review) it is advised to always do the null-check on variables returned by that code unless the documentation says the opposite. If we are sure that we want to check if list is empty we have two scenarios: