I was playing with automatic vs dynamic memory allocation for the linked list node. The following code represents the minimal working example.
The following code works and prints the result I expect:
list 1:
1 
list 2:
2 
list 3:
1 2 
Code:
#include <iostream>
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* merge_two_lists_iter(ListNode* l1, ListNode* l2) {
    ListNode* res = nullptr;
    res = new ListNode(l1->val);
    res->next = new ListNode(l2->val);
    return res;
}
void print_list(ListNode* l) {
    while (l) {
        std::cout << l->val << " ";
        l = l->next;
    }
    std::cout << std::endl;
}
int main() {
    // List l1 consists of one node with value 1
    ListNode* l1 = new ListNode(1);
    // List l2 consists of one node with value 2
    ListNode* l2 = new ListNode(2);
    // List l3 is l1 and l2 merged
    ListNode* l3 = merge_two_lists_iter(l1, l2);
    std::cout << "list 1:" << std::endl;
    print_list(l1);
    std::cout << "list 2:" << std::endl;
    print_list(l2);
    std::cout << "list 3:" << std::endl;
    print_list(l3);
    return 0;
}
However, when I replace the line res = new ListNode(l1->val); with the following:
ListNode test (l1->val);
res = &test;
The l3 seems to consist of some random values:
list 1:
1 
list 2:
2 
list 3:
-1845946528 -272632592 -2092384207 (lldb)
I tried to debug the merge_two_lists_iter function and the l3 looks correct. However, the print_list function prints some random values. I would really appreciate if someone could ELI5 what is going on here.
 
    