I'm learning bison/yacc (and reviewing some c as well) and trying to build a json parser as simple test project.
Using the terminology found on http://www.json.org/ I have a struct pair that represents a string/value pair and a struct object representing an object that has a members field that contains basically a pointer to a linked list of pairs.
I have a simple c function (create_pair) that returns a new pair. I noticed a weird behaviour that I'm not able to explain:
- If I call such function from the "main" and I print the memory address of returned structs their address is always different.
- If I call the very same function inside a bison "action" I see that my function returns a pointer that happens to reside always on the very same memory address.
Does this make any sense?
Details/Code follow:
here's the code (the link, contains a list of 4 pastebin links pointing to the four different files included in the "project"):
you can compile and run it with:
lex t.l
yacc -d t.y
cc y.tab.c lex.yy.c t.c
./a.out
If you launch the code and run it with the following input:
{ "firstName": "A", "lastName": "B" }
you'll see that:
1) the code executed in "main" (check file t.y), creates four different pair objects, I then print their memory address and the output is something like (notice different addresses):
p 0x7fff52476be8 //(<-memory address for pair p)
print pair: P, Hellov
q 0x7fff52476bc8 //(<-memory address for pair q)
print pair: Q, Hellox
2) as soon as I paste the json sample above we hit the "pair" rule twice, the first time for "firstName": "A", the second time for "lastName": "B", I create a new pair in both cases and print the memory address, and they are the same:
Creating pair 0x7fff52475c88
print pair: firstName, A
Creating pair 0x7fff52475c88
print pair: lastName, B
Why does this happen?