I made a function on how to reverse a singly linked list recursively in C.
the function is as below.
struct node * reverseSLL2(struct node *p,struct node
When a non-void function returns without a return statement, it is Undefined Behaviour (UB). Make sure to avoid this.
However, the function still might return something even without using the return statement. For example, on x86 architectures, the function will return whatever is there in the eax
register, which will most probably be one of the local variables.
This is undefined behavior. Compiling the code should produce a warning about reaching the end of a function through a code path that is missing a return
.
The reason you do not see that the function is broken, and observe it producing the right results, is because the actual value that is returned from the base case branch (i.e. the else
) does have a correct return
. It is possible that the compiled code reuses that last return value in all invocations of the function up the stack, so the caller ends up getting the intended value.
However, the code is invalid. You should add return
in front of the recursive call to fix the problem:
return reverseSLL2(temp1,p);
I'll bet you're running on a machine where the function result is in a register (EAX on 32-bit x86 for example), and the return value from the recursive call is still sitting in that register when you return without a value by falling off the end of the function. The compiler doesn't have to use that sequence, so it's still Undefined Behavior.
You can fix your version by simply adding the return to the recursive call:
return reverseSLL2(temp1,p);