The tab Memory of the debugger draws the frames and the objects their variables point to, with arrows: Python lists and objects, C pointers down a linked list to NULL, and warnings when allocated heap blocks are never freed.
Python
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
numbers = [5, 2, 8]
same = numbers
same.append(1)
head = Node(1, Node(2, Node(3)))
print(numbers, head.next.value)
C
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
int main(void)
{
struct node *head = NULL;
for (int i = 3; i >= 1; i--) {
struct node *n = malloc(sizeof *n);
n->value = i;
n->next = head;
head = n;
}
for (struct node *p = head; p != NULL; p = p->next) {
printf("%d ", p->value);
}
printf("\n");
while (head != NULL) {
struct node *next = head->next;
free(head);
head = next;
}
return 0;
}
Student
- Step through the Python example and open Memory:
numbersandsamepoint to the same list, soappendchanges both. - In C, follow
headafter eachmalloc: the list grows at its front. Remove thefree(head);line and Step to the end to see the heap leak warning.
Teacher
- Good for aliasing, mutable lists, recursion, pointers and dynamic memory management.