Skip to content

Instantly share code, notes, and snippets.

@sonald
Created March 5, 2015 03:51
Show Gist options
  • Save sonald/4feb2dc07022120ff304 to your computer and use it in GitHub Desktop.
Save sonald/4feb2dc07022120ff304 to your computer and use it in GitHub Desktop.
type-punning ans strict aliasing
#include <stdio.h>
#include <stdlib.h>
/**
* gcc -O2 will cause `tail = (Node*)&list;` to be optimized out, will give list === null
*/
typedef struct Node_ {
struct Node_* next;
int val;
} Node;
int main(int argc, char *argv[])
{
Node *list, *tail, *n;
list = NULL;
tail = (Node*)&list;
for (int i = 0; i < 10; i++) {
n = (Node*)malloc(sizeof(Node));
n->val = i;
n->next = NULL;
tail->next = n;
tail = n;
}
if (list == NULL) {
printf("list is null?\n");
} else {
printf("list: ");
n = list;
while (n) {
printf("%d ", n->val);
n = n->next;
}
putchar('\n');
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment