DEV Community

Andrew (he/him)
Andrew (he/him)

Posted on

Today I Learned: Pointer Swizzling

"In computer science, pointer swizzling is the conversion of references based on name or position to direct pointer references. It is typically performed during the deserialization (loading) of a relocatable object from disk, such as an executable file or pointer-based data structure. The reverse operation, replacing pointers with position-independent symbols or positions, is sometimes referred to as unswizzling, and is performed during serialization (saving)."
[ Wikipedia ]

Pointer unswizzling is the process of turning pointers into useful information during serialization (saving an object to disk). In programming languages with pointers, you might -- for example -- implement a singly-linked list like

struct node {
  int data;
  struct node *next;
};
Enter fullscreen mode Exit fullscreen mode

where next is a pointer to the next node in the list. We traverse the list by dereferencing next to get the next node, from which we can get the following node, and so on.

But saving this linked list to disk (serializing it) as-is wouldn't make sense. We serialize data to share it across a network, or save it to a database, or share it with someone else. In any of these cases, the specific addresses at which the list nodes were originally stored are irrelevant. And since we aren't storing their addresses in the serialized form, we can't link the pointers to the nodes in the saved data.

Instead, we usually unswizzle pointers by turning them into more useful information, like -- for example -- node indices:

struct node_saved {
  int data;
  int id_number;
  int id_number_of_next_node;
};
Enter fullscreen mode Exit fullscreen mode

This way, we can tell the ordering of the nodes, even when they've been saved to disk. The opposite process, pointer swizzling involves turning these indices back into pointers during deserialization, so the node can be used again as though they weren't serialized and deserialized at all.

Top comments (1)

Collapse
 
timclicks profile image
Tim McNamara

How did you stroll across that concept? What a great name!