Home > Blockchain >  Why is the next field explicitly set to null?
Why is the next field explicitly set to null?

Time:10-15

I was watching this Computerphile Video. In the description, this code was posted.

In the code provided,

THING *newelement(char *text)
{
    THING *newp;
    newp = (THING *) malloc (sizeof(THING));
    newp->item = (char *)malloc(strlen(text)   1);
        strcpy(newp->item, text);
        newp -> next = NULL;
    return newp;
}

they had this method. In this method, there is a line newp -> next = NULL. Why do we have to explicitly set the next field equal to null.

I thought about this as follows. The bottom line is that we are returning a pointer to this struct to the user. The user knows that they have provided the method with text but no next reference. Regardless of whether or not we set the next reference to null, if the user chooses to dereference the next field, either a segfault will happen or undefined behavior will occur which are both undesirable.

CodePudding user response:

if the user chooses to dereference the next field...

If the user is able to check whether the next field is invalid, they probably won't dereference it because they supposedly know that dereferencing an invalid pointer is "bad" (can cause a segfault or read garbage data). Thus, if you set next to NULL, you enable the user to check whether the field is valid or not.

If you leave it uninitialized (or rather, initialized with whatever garbage data malloc provided), the user will be left assuming that the pointer is valid, because you can't guarantee that it'll be NULL.

  • Related