From your code, I'm guessing that each node represents a single digit. Consider that you are trying to add two numbers, and one number is 1 digit longer than the other. Let's assume temp1 is the pointer for the list that holds the longer number.
Eventually, you'll have temp1 pointing at something, while temp2 is null.
45 46
|
temp1 = temp1->next;
temp2 = temp2->next;
|
In that case, what does the above code do? It reads the node pointed at by temp1, finds its next pointer, then copies it to temp1. That is fine.
But what about the next line? It tries to read the node pointed at by temp2, but temp2 is pointing at null! it cannot get the next pointer from that, so it is an illegal operation.
What you should is change the loop to
while (temp1 != NULL && temp2 != NULL)
. After that loop, you should have two other loops
while (temp1 != NULL)
and
while (temp2 != NULL)
. Only one of those later loops will run, and you'll just add the remaining digits of the longer number to result.