Handmade Network»Forums
40 posts
Question about linked list pointer/memory corruption
Edited by BernFeth on Reason: Initial post
Hey guys,

I have been learning to program in C for the past few years and always used Casey’s approach to memory management - allocate a big memory “pool” at start and use memory arenas with PushSizes and stuff - also I use his scheme for temporary memory (I haven’t gone too far in the series yet so I just use basic push only scheme that Casey uses at start).

In between experimentations something has often come up - memory gets corrupted somehow - usually involving a linked list of some sort.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
typedef struct node
{
	int Value;

	struct node *Next;
} node;

typedef struct list
{
	node *Head;

} list;


With list being stored at a fixed size memory arena, I don’t quite understand how that works - it seems to me that node would grow recursively - since every node has a pointer to another node inside it.

Does that “recursive nature” of it mean you can’t actually put the “Next” pointer in any place other than the end of the struct? I recall Casey said something about this at the very start of the series - but I’m not sure this is what he was referring to.

1
2
3
4
5
6
7
8
9
typedef struct world
{
	list *MyList;

	int MoreStuff;
	
	// …

} world;


List stored in a struct with more stuff after it - that’s when memory gets corrupted?
Mārtiņš Možeiko
2562 posts / 2 projects
Question about linked list pointer/memory corruption
Your struct node only contains pointer to other node, not actual node value. So it does not grow recursively. It just points to wherever you make it point to.

If it makes easier for you to think about memory contents for struct node - simply think of that "next" member as 64-bit integer. Remember that pointer is just a number (64-bit on x64 architecture, or 32-bit on x86) that represents address in memory. So your struct node simply contains 64-bit number for "next" member. By making its type pointer to struct node you simply instruct compiler that you'll be accessing bytes it points to as "struct node" type.

This "next" pointer member can be at any location in struct - the order of members does not matter in this situation.
40 posts
Question about linked list pointer/memory corruption
mmozeiko

Remember that pointer is just a number (64-bit on x64 architecture, or 32-bit on x86) that represents address in memory. So your struct node simply contains 64-bit number for "next" member. By making its type pointer to struct node you simply instruct compiler that you'll be accessing bytes it points to as "struct node" type.


Ah! Now I see how that is working.

I'm not sure what I must have done in the times I got garbage data in my gamestate after messing around with that.

Probably wrote after the end of an array or something I'm guessing,

Anyway, thanks for the explanation Martins!