1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
/* Linked list that emulates a hash map */ # include <stdlib.h> # include <stdio.h> # include <string.h> # define LEN_NAME 30 /* Maximun length for a given name */ void **L = NULL; /* points to the first node of the linked list */ void new(); /* Inserts a new node */ void print(); /* Prints the contents of the linked list */ /* test code */ int main(void) { new(); printf("Values: %s %d\n", (char *)(*L), *((int *)(*(L+1)))); print(); return 0; } /* Inserts a new node */ void new() { void *node[3]; /* A new node */ /* Initialize all the pointers */ node[0] = malloc(LEN_NAME); /* First element is the name of someone... */ strcpy((char *)(node[0]), "Pablo"); node[1] = malloc(sizeof(int)); /* ...second is his age... */ *((int *)(node[1])) = 19; node[2] = malloc(2); /* ...ant the third is a pointer to the next node */ (node[2]) = NULL; L = node; } /* Prints the contents of the linked list */ void print() { printf("Values: %s %d\n", (char *)(*L), *((int *)(*(L+1)))); }
Refactorings
No refactoring yet !
jonathantan86
October 13, 2007, October 13, 2007 23:26, permalink
Because L now points to a location on the stack after you call new. When you call print, print's stack frame overwrites the location which L points to, so you get garbage.
Conrad
October 14, 2007, October 14, 2007 00:13, permalink
You are allocating the array in the stack and trying to use it outside of the scope. Change your node allocation to this and it should work.
New Allocating Code
1
void **node = malloc(sizeof(void *) * 3); /* A new node */
I was in the middle of this, when something weird happened...
Here is the output:
Values: Pablo 19
Values: 134520840
Can anybody tell me why print() doesn't work?
Thanks