Home > Net >  Why doesn't memory blow up for an infinite pointer chain in C ?
Why doesn't memory blow up for an infinite pointer chain in C ?

Time:06-18

Beginner question: In relation to this original question here, every variable we generate has a memory address to it, and the pointer holds that memory address. The pointer itself also has its own memory address. Why doesn't this recursively generate an infinite chain of memory-addresses that hold other memory-addresses until your memory (that holds all these memories) blow up, whenever you declare just a single variable? What am I missing here?

CodePudding user response:

What am I missing here?

The names of the pointers.

An expression like &(&a) is not valid; there needs to be a name for an address before you can take the address again. (There are more precise ways to express that, but the more precise ways can also be more confusing at this stage.)

In the linked-to question, there is a variable with a name.

int a = 10;

This variable has a value (a) and an address (&a). However, the address is not itself necessarily stored in memory until it is given a name.

int *p = &a;

At this point, there is the value a, the address of that value (&a stored in p), and the address of a pointer to that value (&p). However, the address of p is not necessarily stored in memory until it is given a name.

int **q = &p;

And so on.

Yes, you could theoretically have an unbounded chain of these names, but each name is necessary. If you stop generating names, you stop getting things to take the address of. Even if you find a way to get the compiler to generate names for you (so you don't have to type each out, which would take forever), the compiler will stop generating those names once it hits one of its internal limits. So, possible in theory, but not in practice.

  •  Tags:  
  • c
  • Related