I saw this code in C++ - it is used to add two linked lists.
The addTwoNumbers function defines a head which is a struct pointer and its next member is a struct. Eventually the function returns the next member of head. Both were initialized on the stack (without using malloc) so how is it possible that the returned value points to a valid address after function execution frame was removed from the stack? Thanks ahead for explanation :)
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) {}
};
ListNode *somFunc()
{
ListNode *tail = new ListNode(2);
ListNode *head = new ListNode(12, tail);
return head->next;
}
int main(int argc, char **argv)
{
ListNode *res = somFunc();
return 0;
};