5

In C, are the following well-defined?

void* ptr = &ptr;
void* array[1] = {array};

In other words, can you use the address of a variable to initialize that variable? It seems to work with the GCC compiler, but I just want to know whether it is something I can rely on.

Edit: this is essentially a duplicate of Defining a pointer to refere to same variable name's reference?

Community
  • 1
  • 1
  • 2
    Why do you think it might not work? Looks legal to me. It's like to have numbered boxes containing their own numbers written on a piece of paper inside... – Eugene Sh. Oct 04 '16 at 19:58
  • Or you are worried about the variable not to have an address at the time initializer is evaluated? – Eugene Sh. Oct 04 '16 at 20:15
  • "Well-defined" might be stretching it, but I can't anything that definitively says it would be undefined. `void *` is special, but I don't know if that specialness extends to `void **`. – John Bode Oct 04 '16 at 20:16
  • 1
    Well. No restriction about this in the [standard (6.7.9)](http://port70.net/~nsz/c/c11/n1570.html#6.7.9). And if it is not forbidden, it is allowed.. – Eugene Sh. Oct 04 '16 at 20:23
  • 1
    Possible duplicate of [Defining a pointer to refere to same variable name's reference?](http://stackoverflow.com/questions/25683034/defining-a-pointer-to-refere-to-same-variable-names-reference) – ecatmur Oct 04 '16 at 22:36
  • Logically, `&ptr` would be a `void**`, and you're assigning that to a `void*`. IMHO this shouldn't work. But as the other comments show, it may be legal. – Charles Oct 05 '16 at 00:26

2 Answers2

0

It SHOULD be legal. Since ptr is not const, its initialization value is not fixed in the .text code area, and so it should be known at run time and written in RAM with the correct value.

0

This is perfectly fine. One way to understand it is the following equivalent snippet:

void* ptr = NULL;
void* ptr_to_ptr = &ptr;
ptr = ptr_to_ptr;

void* array[1] = {NULL};
void* array_ptr = array;
array[0] = array_ptr;

void* is special and a pointer to it is still void*

A more practical example of referencing a variable in its own assignment:

int *x = malloc(sizeof(*x));
static_assert(sizeof(*x) == sizeof(int), "broken compiler");
Abdullah
  • 711
  • 7
  • 5