How does a compiler string together addresses in a linked list?

-2

How does a compiler know which nodes to point to next in a linked list since each node's next or previous can be anywhere in the heap. Can i attach a specific memory address say 0x00000001 to a pointer and bind it to that address?

c++
linked-list
asked on Stack Overflow Sep 19, 2019 by Tarun Kumar • edited Sep 25, 2019 by Tarun Kumar

1 Answer

1

Also, can you bind a specific address to a pointer?

Yes. In fact, that is precisely the purpose of a pointer. Memory is addressed by numbers. The first byte is in the address 0, the next is 1 and so on. A pointer is essentially an object that stores a memory address, which is internally simply a number.

In following example, we store the address of the object i into a pointer:

int i;
int* ptr = &i;

How does a compiler string together addresses in a linked list

A linked list node is simply a structure with a pointer to the next (and previous in case of doubly linked list) node. The address of the next node is stored in the pointer.

how does the compiler allocate [...] these addresses during runtime?

In whatever way the language implemnetation chooses to allocate. The language does not specify "how" memory is allocated. The way will differ depending on the storage duration class of the object.

Typically in practice, the language implementation will ask the operating system to map some memory. Variables with automatic storage are stored in what is called the "call stack", and dynamic objects are stored in "free store". How either of these are implemented is outside the scope of my answer. I would suggest studying how operating systems and compilers are made. It's a wide topic.

how does the compiler [...] reference these addresses during runtime?

It stores the address. There are CPU instructions for accessing memory at given address.

Can I for example , bind 0x00000001 to node3?

I don't know what "node3" is, but you can point at the address 1 if you want to. There's not much you can do with the pointer unless there actually is an object at the address. There's no way of creating objects into unallocated memory, and there is no way of allocating memory from arbitrary address in standard C++.

answered on Stack Overflow Sep 19, 2019 by eerorika • edited Sep 19, 2019 by eerorika

User contributions licensed under CC BY-SA 3.0