34

Suppose I want to get the last element of an automatic array whose size is unknown. I know that I can make use of the sizeof operator to get the size of the array and get the last element accordingly.

Is using *((*(&array + 1)) - 1) safe?

Like:

char array[SOME_SIZE] = { ... };
printf("Last element = %c", *((*(&array + 1)) - 1));
int array[SOME_SIZE] = { ... };
printf("Last element = %d", *((*(&array + 1)) - 1));

etc

27
  • 4
    I don't think so. *(array+1) is equal to array[1].
    – Spikatrix
    Sep 12, 2015 at 9:59
  • 7
    I think &array+1 is still OK but you're hitting UB at *(&array+1) because that's dereferencing a pointer one past the end of the array variable (but I'm not sure about this).
    – melpomene
    Sep 12, 2015 at 10:04
  • 4
    In bracket notation this is (&array)[1][-1]. So (as a quick assessment) I don't think it is valid - the past-the-end pointer is dereferenced.
    – M.M
    Sep 12, 2015 at 10:05
  • 5
    @Xis88 Safe because sizeof (mostly) doesn't evaluate its operand, it only looks at its type (exception: VLAs).
    – melpomene
    Sep 12, 2015 at 10:08
  • 10
    I don't know if it's legal or not, but I do know that code maintainers will kill you because of this code. Sep 12, 2015 at 14:03

6 Answers 6

21

No, it is not.

&array is of type pointer to char[SOME_SIZE] (in the first example given). This means &array + 1 points to memory immediately past the end of array. Dereferencing that (as in (*(&array+1)) gives undefined behaviour.

No need to analyse further. Once there is any part of an expression that gives undefined behaviour, the whole expression does.

25
  • 2
    But array[sizeof(array)/sizeof(array[0])-1] would be safe, right?
    – user2933244
    Sep 12, 2015 at 10:13
  • 10
    Sure, but that has nothing to do with the question.
    – Peter
    Sep 12, 2015 at 10:14
  • 2
    It's related because it does the same thing safely. Sorry for my curiousity.
    – user2933244
    Sep 12, 2015 at 10:14
  • 3
    @Peter: the "1-array-long" object clause is under pointer arithmetic. For example in N3690 it's numbered 5.7/4, "For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type." If you want to find it in a different version of the standard, I think that section is always called "additive operators", but I might be wrong. Sep 13, 2015 at 11:13
  • 3
    @Enzo: What about the text "If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated." which you have highlighted in bold font do you not understand? The wording "shall not" in a standard means that the result of doing otherwise is undefined.
    – Peter
    Sep 14, 2015 at 13:56
18

I don't think it is safe.

From the standard as @dasblinkenlight quoted in his answer (now removed) there is also something I would like to add:

C99 Section 6.5.6.8 -

[...]
if the expression P points to the last element of an array object, the expression (P)+1 points [...]
If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

So as it says , we should not do this *(&array + 1) as it will go one past the last element of array and so * should not be used.

As also it is well known that dereferencing pointers pointing to an unauthorized memory location leads to undefined behaviour .

17
  • 1
    Ah. So I guess it is UB. Thanks!
    – Spikatrix
    Sep 12, 2015 at 11:01
  • I somewhat doubt it. It hangs a bit on what 'evaluated unary * operator' means. I don't think the inner * is evaluated in that way.
    – MicroVirus
    Sep 12, 2015 at 11:03
  • 1
    What if he has an int[3][2] and his array is actually the first element? What if he has an int[6] which he pointer-casted to int[3]? Uhm, these wonderful committees... :-(
    – peterh
    Sep 12, 2015 at 11:45
  • 1
    @peterh C is defined by a standards document, not some particular assembly. Generally, casting pointers may change their size and value. Just because you have only worked on a flat memory model system, don't assume that is the only type of system.
    – M.M
    Sep 12, 2015 at 11:51
  • 2
    The only way out is if the unary * operator here isn't evaluated. I believe that there's always been some rumbling about whether &*foo and other similar constructions including this one, should or should not evaluate the unary * (that's "should" in the sense of "what do we want to write in the standard"). The C standard added some special language about &*, and I don't think C++ has, but (a) I may have misremembered and (b) I'm really not very familiar with C++14 at all. Sep 13, 2015 at 11:17
13

I believe it's undefined behavior for the reasons Peter mentions in his answer.

There is a huge debate going on about *(&array + 1). On the one hand, dereferencing &array + 1 seems to be legal because it's only changing the type from T (*)[] back to T [], but on the other hand, it's still a pointer to uninitialized, unused and unallocated memory.

My answer relies on the following:

C99 6.5.6.7 (Semantics of additive operators)

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

Since &array is not a pointer to an object that is an element of an array, then according to this, it means that the code is equivalent to:

char array_equiv[1][SOME_SIZE] = { ... };
/* ... */
printf("Last element = %c", *((*(&array_equiv[0] + 1)) - 1));

That is, &array is a pointer to an array of 10 chars, so it behaves the same as a pointer to the first element of an array of length 1 where each element is an array of 10 chars.

Now, that together with the clause that follows (already mentioned in other answers; this exact excerpt is blatantly stolen from ameyCU's answer):

C99 Section 6.5.6.8 -

[...]
if the expression P points to the last element of an array object, the expression (P)+1 points [...]
If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

Makes it pretty clear that it is UB: it's equivalent to dereferencing a pointer that points one past the last element of array_equiv.

Yes, in real world, it probably works, as in reality the original code doesn't really dereference a memory location, it's mostly a type conversion from T (*)[] to T [], but I'm pretty sure that from a strict standard-compliance point of view, it is undefined behavior.

25
  • 9
    @EnzoFerber That's exactly the problem: you somehow think it's ok to do computation on invalid addresses. On the contrary; in some (most?) cases, computations involving unallocated addresses are UB. For example, just the simple fact of computing a pointer address that is not a pointer to an element in an array or one past the end is UB. It doesn't matter if you're not going to use it; it's UB (although it will probably work in most platforms). This example is not relevant for this question, but it shows that your assumption is wrong to begin with. Sep 12, 2015 at 14:21
  • 4
    @EnzoFerber That is to say: in general, you must be really careful about your assumptions if you want strict standard conformance. I'm not saying I disagree with your answer. I fully understand your point of view, and I agree that in practice it's probably harmless to do (*(*(&a + 1)-1)), and I understand why you say so, but if we're here to be technically correct and we want to play by the standard rules, sometimes we need to back off a little bit and really play by the book. The question is mostly about: from a standard-compliant point of view, is this guaranteed to work? Sep 12, 2015 at 14:27
  • 2
    @LarsFriedrich that's also UB. dblptr++ is ok, but dereferencing it is UB. It's the exact same thing. Sep 12, 2015 at 20:28
  • 1
    Based on the votes of answers, I think that it is not safe to use it. Your answer good and includes explanations as well as quotes from the standard. So, I accept it. Thanks!
    – Spikatrix
    Sep 13, 2015 at 7:18
  • 5
    @EnzoFerber I get it. I really do. As I said, I fully understand your point of view and your answer. I know that dereferencing &array + 1 looks harmless precisely because it's a type-conversion operation. And I'm pretty sure it's ok in most, if not all, machines out there. But the way I see it, there's nothing in the standard that guarantees this behavior. I honestly think it's a glitch in the standard, which leads different people to different conclusions - I think it's nonsense to keep discussing it, as clearly none of us will agree in the near future. Formally, I classify it as UB. Sep 14, 2015 at 16:40
2

It is probably safe, but there are some caveats.

Suppose we have

T array[LEN];

Then &array is of type T(*)[LEN].

Next, &array + 1 is again of type T(*)[LEN], pointing just past the end of the original array.

Next, *(&array + 1) is of type T[LEN], which may be implicitly converted to T*, still pointing just past the end of the original array. (So we did NOT dereference an invalid memory location: the * operator is not evaluated).

Next, *(&array + 1) - 1 is of type T*, pointing at the last array location.

Finally, we dereference this (which is legitimate if the array length is not zero): *(*(&array + 1) - 1) gives the last array element, a value of type T.

Note that the only time we actually dereference a pointer is in this last step.

Now, the potential caveats.

First, *(&array + 1) formally appears like an attempt to dereference a pointer that points to an invalid memory location. But it really isn't. That's the nature of array pointers: this formal dereference only changes the type of the pointer, does not actually result in an attempt to retrieve value from the referenced location. That is, array is of type T[LEN] but it may be implicitly converted to type &T, pointing to the first element of the array; &array is a pointer to type T[LEN], pointing at the beginning of the array; *(&array+1) is again of type T[LEN] which may be implicitly converted to type &T. At no point is a pointer actually dereferenced.

Second, &array + 1 may in fact be an invalid address, but it really isn't: My C++11 reference manual tells me explicitly that "Taking a pointer to the element one beyond the end of an array is guaranteed to work", and a similar statement is also made in K&R, so I believe it has always been standard behavior.

Finally, in case of a zero-length array, the expression dereferences the memory location just before the array, which may be unallocated/invalid. But this issue would also arise if one used a more conventional approach using sizeof() without testing for nonzero length first.

In short, I do not believe there is anything undefined or implementation-dependent about this expression's behavior.

11
  • 1
    This answer looks more like "If the compiler does what I think it should do, this won't emit any assembly instructions that access invalid memory" rather than "The standard guarantees that this does what I think it should do".
    – user1084944
    Sep 12, 2015 at 20:04
  • 1
    (&array+1) is a pointer that is dereferenced (in the sense of what the C and C++ languages mean by "dereferenced", not the sense that "the compiler has emitted a load-from-memory assembly instruction")
    – user1084944
    Sep 12, 2015 at 20:18
  • 1
    In C, *&array is an "lvalue of type int[LEN]". The C++ standard also has the same wording. (also, &array is a pointer, and you apply unary * to it: that's what dereferencing means) (editing: errors in this comment)
    – user1084944
    Sep 12, 2015 at 20:45
  • 1
    In C11's exact wording is if it points to an object, the result is an lvalue designating the object. If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’
    – user1084944
    Sep 12, 2015 at 20:54
  • 1
    You have to provoke it first. *&array really can't hope to be T* itself; otherwise you'd get totally the wrong thing with &*&array (which is a pointer-to-array-of-T) or sizeof *&array (which is the size of array-of-T). Also, lvalue is not a synonym for "can be assigned to": some relevant prhases are A modifiable lvalue is an lvalue that does not have array type... and An assignment operator shall have a modifiable lvalue as its left operand
    – user1084944
    Sep 12, 2015 at 21:04
1

Imho that might work but is probably unwise. You should carefully review your sw design and ask yourself why you want the last entry of the array. Is the content of the array completely unknown to you or is it possible to define the structure in terms of c structs and unions. If that is the case stay away from complex pointer operations in a char array for example and define the data properly in you c code, in structs and unions where ever possible.

So instead of :

 printf("Last element = %c", *((*(&array + 1)) - 1));

It could be :

 printf("Checksum = %c", myStruct.MyUnion.Checksum);

This clarifies your code. The last letter in your array means nothing to a person not familiar with whats in this array. myStruct.myUnion.Checksum makes sense to anyone. Studying the myStruct structure could explain the whole data structure to anyone. Please use something like that if it can be declared in such a way. If you are in the rare situation you can not, study above answers, they make good sense i think

-2

a)

If both the pointer operand and the result [of P + N] point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow;
[...]
if the expression P points either to an element of an array object or one past the last element of an array object, and the expression Q points to the last element of the same array object, the expression ((Q)+1)−(P) has the same value as ((Q)−(P))+1 and as −((P)−((Q)+1)), and has the value zero if the expression P points one past the last element of the array object, even though the expression (Q)+1 does not point to an element of the array object.

This states that computations using array elements one past the last element is actually completely fine. As some people here have written that the use of non-existent objects for computations is already illegal, I thought I include that part.

Then we need to take care about this part:

If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

There is one important part that the other answers omitted and that is:

If the pointer operand points to an element of an array object

This is not the fact. The pointer operand we dereference is not a pointer to an element of an array object, it is a pointer to a pointer. So this whole clause is completely irrelevant. But, there is also stated:

For the purposes of these [additive] operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

What does this mean?

It means our pointer to a pointer is actually again a pointer to an array - of length[1]. And now we can close the loop, because as the first paragraph states, we are allowed to make calculations with one past the array, so we are allowed to make calculations with the array as if it would be an array of length[2]!

In a more graphical way:

ptr -> (ptr to int[10])[0] -> int[10]
    -> (ptr to int[10])[1]

So, we are allowed to make calculations with (ptr to int[10])[1], even though it is technically outside the array of length[1].

b)

The steps that happen are:

array ptr of type int[SOME_SIZE] to the first element array

&array ptr to a ptr of type int[SOME_SIZE] to the first element of array

+ 1 ptr, one more than the ptr of type int[SOME_SIZE]) to the first element array, to a ptr of type int

This is NOT yet a pointer to int[SOME_SIZE+1], according to C99 Section 6.5.6.8. This is NOT yet ptr + SOME_SIZE + 1

* We dereference the pointer to the pointer. NOW, after the dereferencing, we have a pointer according to C99 Section 6.5.6.8, which is past the element of the array and which is not allowed to be dereferenced. This pointer is allowed to exist and we are allowed to use operators on it, except the unary * operator. But we don't use that one on that pointer yet.

-1 Now we subtract one from the ptr of type int to one after the last element of the array, letting ptr point to the last element of the array.

* dereferencing a ptr to int to the last element of the array, which is legal.

c)

And last, but not least:

If it would be illegal, then the offsetof macro would be illegal, too, which is defined as:
((size_t)(&((st *)0)->m))

20
  • Individual objects count as length-one arrays for the purpose of this arithmetic. array is an object of type int[SOME_SIZE], and &array + 1 is a past-the-end pointer, thus dereferencing it is UB.
    – user1084944
    Sep 12, 2015 at 19:20
  • &array+1 is not a pointer past-the-end of the array, it is a pointer to a pointer. We do not dereference a pointer past-the-end of the array. Did you actually read my answer? Sep 12, 2015 at 19:23
  • 1
    I'm pretty sure these "nitpicks" contribute directly into your error, otherwise I wouldn't have bothered. But I have no problem with ceasing to try and correct it.
    – user1084944
    Sep 12, 2015 at 21:02
  • 2
    offsetof is not defined as ((size_t)(&((st *)0)->m)). That is how some compilers implement it, on some computers. That implementation is undefined behavior, but that's OK in an implementation of the standard library. The implementors of that library know exactly which compiler the library will used with (theirs), and they know exactly what that compiler will do in response to this construct. The authors of the standard library can get away with invoking undefined behavior. You cannot. Sep 12, 2015 at 21:35
  • 1
    @LarsFriedrich: A NULL pointer is not undefined behavior, true, but using -> on a NULL pointer, even if you are only doing so to take the address of the result, is undefined behavior. And yes, I believe they are saying that the header file of the standard library need not conform to standard C; as far as I know, as far as the standard is concerned, it doesn’t need to be a real file or be written in C at all as long as the #include introduces the correct prototypes/declarations/macros/types/etc. into the namespace.
    – icktoofay
    Sep 12, 2015 at 23:36

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.