Runtime error member access within null pointer of type

struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool hasCycle(ListNode *head) { if(head == NULL) return false...
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == NULL) return false;
        ListNode* walker = head;
        ListNode* runner = head;
        while(runner->next != NULL && walker->next != NULL){
            walker = walker->next;
            runner = runner->next->next;
            if(walker == runner) return true;
        }
        return false;
    }
};

I was practicing an interview code which seemed to be pretty simple. I have to return a bool that determines whether or not the singly-linked list has a cycle. I made two pointers walker which moves 1 step and runner which moves 2 steps every iteration.

But then this code gave me an error:

Line 15: member access within null pointer of type 'struct ListNode'

What causes that error?

Stargateur's user avatar

Stargateur

23k8 gold badges59 silver badges84 bronze badges

asked Jun 24, 2017 at 7:31

Dukakus17's user avatar

4

You only make sure that runner->next is not null, however after assignment

runner = runner->next->next;

runner can become null.

answered Jun 24, 2017 at 7:36

user7860670's user avatar

user7860670user7860670

34.8k4 gold badges55 silver badges82 bronze badges

2

This should solve it:

bool hasCycle(ListNode *head) {
    if(head == NULL || head->next == NULL) { return false; }
    struct ListNode * walker = new ListNode(1);
    struct ListNode * runner = new ListNode(2);
    walker = head;
    runner = walker->next;
    while(walker != fast){
        if(runner == NULL || runner->next == NULL) { return false; }
        walker = walker->next;
        runner = runner->next->next;
    }
    return true;
}

answered Aug 5, 2020 at 3:02

csg's user avatar

csgcsg

8,0383 gold badges13 silver badges37 bronze badges

0

//- If a loop from circular path then there is hundred% chance that they will going to meet at some point so here we are taking a walker which move one step and a runner which move two step.

bool hasCycle(ListNode *head){
if(head == NULL || head->next == NULL)
       return false; 

struct ListNode *temp  = head; 
struct ListNode *walker; 
struct ListNode *runner;
walker = runner= head;
while(temp ){
  walker = walker->next;
  runner = runner->next->next;
    if(runner == walker) // as soon both get at same address we got return as 
     true value.
     { return True; }
    temp = temp->next;
}
return false;

}

answered Aug 21, 2020 at 8:03

Durgesh Rai's user avatar

1

The Below Code should work fine.
It is the classic Hare-Tortoise theorem, where the hare takes 2 steps(distance units) while the tortoise goes by 1.

I think you did not check the nullity of runner->next->next which has caused this error

bool hasCycle(ListNode *head) 
{
    if(head == NULL || head->next == NULL) 
    { 
       return false;
    }
    ListNode* tortoise=new ListNode();
    ListNode* hare = new ListNode();
    tortoise=head;
    hare=tortoise->next;
    while(tortoise != hare)
    {
        if(hare == NULL || hare->next == NULL) 
        { 
           return false; 
        }
        tortoise=tortoise->next;
        hare=hare->next->next;
    }
    return true;
}

AleXelton's user avatar

answered Jun 13, 2021 at 18:22

Debi Prasad's user avatar

Sort answer is here with explanation

It returns the error because runner=runner->next->next can be NULL
and you are checking runner->next!=NULL in while conditioning so you
have to do a little change In your code In order to get your answer In
while condition check for runner->next->next!=NULL and get the right
answer.

Happy Coding :>)

answered Jul 25, 2021 at 13:22

Afroz Quraishi's user avatar

0

I am trying to create a function that will malloc my node pointers but for whatever reason the passed node when accessed after my function throws an error as if the node was not given memory at all. Here is my code:

typedef struct node
{
    bool is_word;
    char chars[N];
    struct node *children[N];
}
node;

node *root;

bool alloc_memory(node *n)
{
    n = malloc(sizeof(node));
    if (n == NULL)
    {
        return false;
    }
    for (int i = 0; i < N; i++)
    {
        n->children[i] = NULL;
    }

    return true;
}

bool load(const char *dictionary)
{
    // Initialize trie
    bool t = alloc_memory(root);
    if (!t)
    {
        return false;
    }

    root->is_word = false;

...
}

At root->is_word = false; I get the following two errors:

runtime error: member access within null pointer of type ‘node’ (aka ‘struct node’)

runtime error: store to null pointer of type ‘bool’

What am I missing to correctly initialize my node with malloc?

Community's user avatar

asked Feb 17, 2019 at 13:22

theurere's user avatar

bool alloc_memory(node *n)

Your parameter n is an independent variable, initialised to whatever you pass to alloc_memory. So any changes to n won’t be reflected in the calling code.

There are at least two common ways around:

  1. Return the pointer, not a boolean. If the pointer returned is NULL, you know something went wrong.
  2. Make the parameter a pointer to pointer to node. That way, you pass the memory address of your pointer you want to have pointing to the new node. The pointer to pointer is still a copy, but the pointee is not.

And I guess you don’t need char chars[N];.

Edit: Some examples what this could look like

  1. Function:

    node *make_node() {
        node *new_node = malloc(sizeof(node));
        if (new_node) {
            // initialise the node
        }
        return new_node;
    }
    

    Calling code:

    node *my_new_node = make_node();
    if (!my_new_node) {
        // something's going terribly wrong
    }
    
  2. Function:

    bool make_node(node **node_ptr) {
        node *new_node = malloc(sizeof(node));
        if (new_node) {
            // initialise the node
    
            *node_ptr = new_node;
            return true;
        } else {
            return false;
        }
    }
    

    Calling code:

    node *my_new_node;
    if (!make_node(&my_new_node)) {
        // something's going terribly wrong
    }
    

answered Feb 17, 2019 at 16:19

Blauelf's user avatar

BlauelfBlauelf

20.8k2 gold badges11 silver badges22 bronze badges

3

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

Hi, I was doing this Merge two sorted linked list question on leetcode and I am getting this runtime error. I am not sure why am I getting this error. Debugging linked list is a hassle and honestly, I was not able to pinpoint the error even after doing debugging (I don’t know much about debugging in the first place).

The code was supposed to merge two sorted linked list

On executing the code, I get the following error

Line 51: Char 23: runtime error: member access within null pointer of type ‘ListNode’ (solution.cpp)

SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:60:23

I searched around and got to know somewhere my code is searching for a null value but I am not sure where. Here is my code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void insertAtTail(ListNode* &newList,int val)
    {
        ListNode* n=new ListNode(val);
        ListNode* temp=newList;
        if(newList==NULL)
        {
            newList=n;
            return;
        }
        while(temp->next!=NULL)
        {
            temp=temp->next;
        }
        temp->next=n;
    }
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* temp1=l1;
        ListNode* temp2=l2;
        ListNode* newList=NULL;
        while(temp1!=NULL && temp2!=NULL)
        {
            if(temp1==NULL && temp2!=NULL)
            {
                insertAtTail(newList,temp2->val);
                temp2=temp2->next;
            }
            if(temp1!=NULL && temp2==NULL)
            {
                insertAtTail(newList,temp1->val);
                temp1=temp1->next;
            }
            if(temp2->val==temp1->val) //This is where I got the error
            {
                insertAtTail(newList,temp1->val);
                insertAtTail(newList,temp2->val);
                temp1=temp1->next;
                temp2=temp2->next;
            }
            if(temp2->val>temp1->val)
            {
                insertAtTail(newList,temp1->val);
                temp1=temp1->next;
            }
            else
            {
                insertAtTail(newList,temp2->val);
                temp2=temp2->next;
            }
        }
        return newList;
    }
};
  • Forum
  • General C++ Programming
  • Force Null Pointer Derefs to Crash?

Force Null Pointer Derefs to Crash?

Hello there!

So if you dereference a null pointer accessing a function of class for example like:

SomeClass *p = nullptr;
p->DoSomething();

This can work perfectly fine as long as the function doesn’t touch member variables.

Or even worse something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>

int g_iGlobalInt = 0;
float g_flGlobalFloat = 0.0f;

class Test
{
public:

	void SetFloatAndInt()
	{
		// m_p is uninitialized, and 'this' is nullptr
		m_p->SetInt();
		m_p->SetFloat();
	}

protected:

	void SetInt()
	{
		g_iGlobalInt = 378;
	}

	void SetFloat()
	{
		g_flGlobalFloat = 222.0f;
	}

private:
	Test *m_p;
};

int main()
{
	Test *p = nullptr;
	p->SetFloatAndInt();

	std::cout << "g_iGlobalInt is: " << g_iGlobalInt << std::endl;
	std::cout << "g_flGlobalFloat is: " << g_flGlobalFloat << std::endl;
	std::cin.get();

	return 0;
}

Which CAN work due to compiler optimization. (Like building in Release mode, this would crash in Debug mode)

To me this is kind of garbage and it can make it harder to track down the actual cause of a crash because there’s some operation done on a bogus pointer somewhere which can be caused by accessing a null pointer like in the example above.

To me if the above behavior is working, that is bad, that is most definitely not something I want.

This is sort of platform specific as far as I know, but I figured I’d ask anyway.

Is there any way to better guarantee desired behavior? I would like it to crash.

Last edited on

wrap it on your own pointer class that does make checks

GCC and Clang has -fsanitize=null which will add checks for null pointers.

test.cpp:36:19: runtime error: member call on null pointer of type ‘struct Test’
test.cpp:13:3: runtime error: member access within null pointer of type ‘struct Test’

https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-fsanitize_003dnull

This option enables pointer checking. Particularly, the application built with this option turned on will issue an error message when it tries to dereference a NULL pointer, or if a reference (possibly an rvalue reference) is bound to a NULL pointer, or if a method is invoked on an object pointed by a NULL pointer.

Last edited on

Wrapping it in my own pointer class wouldn’t be feasible with an existing rather large application in terms of the codebase.

It’s also built with the Microsoft C++ compiler, though I have been interested in clang. I have no idea how difficult it would be to switch everything over. But seeing things like clang-tidy has got me sort of interested.

Topic archived. No new replies allowed.

drinkingWater

14-10-2022

Delete the Middle Node of a Linked List

The problem is pretty straightforward. With the given head of a singly linked list, we delete the middle node. The definition of is given as middle = n/2 where n is the length of the list.
Since it’s a singly linked list, traversal to black is not possible. So, it’s necessary to get to the previous node of middle node or middle — 1.
Since only head is given, a traversal is needed to count the length. Then break the connection.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteMiddle(ListNode* head) {
        if(head->next == nullptr){
            return nullptr;
        }
        int count = 0;
        ListNode* ptr = head;
        ListNode* ptr2 = head;

        while(ptr != nullptr){
            count++;
            ptr = ptr->next;
        }
        for(int i = 0; i < (count / 2) - 1; i++){
            ptr2 = ptr2->next;
        }

        ptr2->next = ptr2->next->next;
        return head;
    }
};

Enter fullscreen mode

Exit fullscreen mode

After accepted I looked for other efficient ways to solve this problem and learnt this new way called Slow pointer Fast pointer
This is a pretty straight forward technic to find middle of a list with unknown size. There is a slow pointer and fast pointer who starts from the beginning. The fast node increments itself twice more than the slow node. As a result, when the fast node already reaches the end, the slow pointer will be at the middle.

With first attempt I ran to an error
runtime error: member access within null pointer of type 'ListNode' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior

for
while(f != nullptr || f->next != nullptr){
f = f->next->next;
s = s->next;
}

Turns out if I need to check both for pointer to be not null.

On the second attempt I got the same error. Because I initialize fast pointer before and if it was a list with length one, it gives us the error for accessing fast->next->next which doesn’t exist.
So, an edge case was necessary.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteMiddle(ListNode* head) {

        if(head->next == nullptr){
            return 0;
        }

        ListNode *s = head;
        ListNode *f = head->next->next;

        while(f != nullptr && f->next != nullptr){
            f = f->next->next;
            s = s->next;
        }

        s->next = s->next->next;
        return head;
        return head;
    }
};

Enter fullscreen mode

Exit fullscreen mode

Reverse String

My approach was simple. Have two pointers at beginning and end. Swap the two pointer and increment and decrement the pointers accordingly.

class Solution {
public:
    void reverseString(vector<char>& s) {
        int l = 0, h = s.size() - 1;
        while(l < h){
            swap(s[l], s[h]);
            l++;
            h--;
        }
    }
};

Enter fullscreen mode

Exit fullscreen mode

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == NULL) return false;
        ListNode* walker = head;
        ListNode* runner = head;
        while(runner->next != NULL && walker->next != NULL){
            walker = walker->next;
            runner = runner->next->next;
            if(walker == runner) return true;
        }
        return false;
    }
};

I was practicing an interview code which seemed to be pretty simple. I have to return a bool that determines whether or not the singly-linked list has a cycle. I made two pointers walker which moves 1 step and runner which moves 2 steps every iteration.

But then this code gave me an error:

Line 15: member access within null pointer of type 'struct ListNode'

What causes that error?

5 Answers

You only make sure that runner->next is not null, however after assignment

runner = runner->next->next;

runner can become null.

This should solve it:

bool hasCycle(ListNode *head) {
    if(head == NULL || head->next == NULL) { return false; }
    struct ListNode * walker = new ListNode(1);
    struct ListNode * runner = new ListNode(2);
    walker = head;
    runner = walker->next;
    while(walker != fast){
        if(runner == NULL || runner->next == NULL) { return false; }
        walker = walker->next;
        runner = runner->next->next;
    }
    return true;
}

//- If a loop from circular path then there is hundred% chance that they will going to meet at some point so here we are taking a walker which move one step and a runner which move two step.

bool hasCycle(ListNode *head){
if(head == NULL || head->next == NULL)
       return false; 

struct ListNode *temp  = head; 
struct ListNode *walker; 
struct ListNode *runner;
walker = runner= head;
while(temp ){
  walker = walker->next;
  runner = runner->next->next;
    if(runner == walker) // as soon both get at same address we got return as 
     true value.
     { return True; }
    temp = temp->next;
}
return false;

}

The Below Code should work fine.
It is the classic Hare-Tortoise theorem, where the hare takes 2 steps(distance units) while the tortoise goes by 1.

I think you did not check the nullity of runner->next->next which has caused this error

bool hasCycle(ListNode *head) 
{
    if(head == NULL || head->next == NULL) 
    { 
       return false;
    }
    ListNode* tortoise=new ListNode();
    ListNode* hare = new ListNode();
    tortoise=head;
    hare=tortoise->next;
    while(tortoise != hare)
    {
        if(hare == NULL || hare->next == NULL) 
        { 
           return false; 
        }
        tortoise=tortoise->next;
        hare=hare->next->next;
    }
    return true;
}

Sort answer is here with explanation

It returns the error because runner=runner->next->next can be NULL
and you are checking runner->next!=NULL in while conditioning so you
have to do a little change In your code In order to get your answer In
while condition check for runner->next->next!=NULL and get the right
answer.

Happy Coding :>)

Понравилась статья? Поделить с друзьями:
  • Rsa operation error
  • Rpgvx rtp ошибка на японском
  • Routing error uninitialized constant
  • Self protection failed error code 4 как исправить
  • Rosemount 8750 loi comm error