I am writing a doubly linked test as an exercise. On adding a node I can test the new node's pointer to the next element for NULL within the function where the node is added, but I can't test for NULL in main function where the function to add a node is called from.
I would expect the snippet below to print: "MAIN:NULL POINTER CHECK WORKS" But it doesn't even though the previous tests in 'add' works. This is because while the new node's next item pointer evaluates to 0 in printf it doesn't evaluate to false in the if statement. What am I missing?
#include <stdio.h>
#include <stdlib.h>
struct elem{
int num;
struct elem *nextElem;
struct elem *previousElem;
};
int add(struct elem *point, int val){
struct elem new = {val, NULL, NULL};
printf("New next pointer - %d\n", (int) new.nextElem);
point->nextElem = &new;
if (!point->nextElem->nextElem){
printf("ADD: Null pointer check works\n");
}
printf("Point next pointer - %d\n", (int) point->nextElem);
return 0;
}
int main(){
struct elem start = {1, NULL, NULL};
add(&start, 2);
if (start.nextElem){
printf("START NEXT ELEM POINTER VALUE: %d\n", (int) start.nextElem->nextElem);
if ( !start.nextElem->nextElem ) {
printf("MAIN:NULL POINTER CHECK WORKS\n");
}
}
}
Output:
New next pointer - 0
ADD: Null pointer check works
Point next pointer - -393574968
START NEXT ELEM POINTER VALUE: 0
CodePudding user response:
Within the function add
you declared the local variable new
with automatic storage duration:
int add(struct elem *point, int val){
struct elem new = {val, NULL, NULL};
printf("New next pointer - %d\n", (int) new.nextElem);
point->nextElem = &new;
//...
After exiting the function the variable will no longer exist (its lifetime will have ended). So the pointer to the variable after exiting the function has an invalid value. Dereferencing the pointer invokes undefined behavior.
You need to allocate dynamically nodes of the list.
Pay attention to that to output a value of a pointer you should use the conversion specifier &p
. For example
printf("New next pointer - %p\n", (void *) new.nextElem);