Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this addition being silently ignored?

I have the following C code:

#include <stdint.h>
#include <stdio.h>

int i;
uint64_t a[] = { (uint64_t)&i, (uint64_t)&i + 0x8000000000000000 };

int main() {
    printf("%p %llx %llx\n", &i, a[0], a[1]);
}

If I compile this (as C or as C++) with Microsoft Visual Studio Community 2015 and then run it, the output is similar to the following:

013E9154 13e9154 13e9154

It seems that the code + 0x8000000000000000, which I expected to set the high bit of a[1], has been silently ignored.

However, if I move the initialization of a inside main, the output is what I would expect:

00179154 179154 8000000000179154

With a global, why is the addition being silently ignored? Should the attempted addition actually set the high bit of a[1] or should it cause a compiler error?

Interestingly, if + 0x8000000000000000 in the above code is replaced by | 0x8000000000000000, I get "error C2099: initializer is not a constant".

Edit: A similar issue can occur even in the absence of casts. Compiled for x64, the following code prints the same value (e.g. 000000013FB8D180) three times:

#include <stdio.h>

int i;
int * a[] = { &i, &i + 0x100000000 };

int main() {
    printf("%p %p %p\n", &i, a[0], a[1]);
}
like image 723
user200783 Avatar asked Oct 07 '16 12:10

user200783


People also ask

What is the meaning of being ignored?

1 : to refuse to take notice of. 2 : to reject (a bill of indictment) as ungrounded.

Why are we ignored?

Here are some reasons you might be ignored by friends:You might be too negative. You might be too high- or low energy compared to your friend. You might talk too much about yourself. You might talk about things your friend isn't interested in.

What are the effects of being ignored?

In fact, the negative effects of being ignored can be long lasting and have been found to lead to health problems, suicidal tendencies, eating disorders, and a reduction in psychological motivation (that is, the initiative that drives us to act on goal oriented behaviors like getting a drink of water when we are ...


1 Answers

The initializer

(uint64_t)&i + 0x8000000000000000

isn't a valid constant expression in C. It is neither an arithmetic constant expression which only allows integer constants, floating constants, enumeration constants, character constants, and sizeof expressions as operands; nor an address constant which doesn't allow casts to integer types.

That said, I'd expect Visual Studio to generate "error C2099: initializer is not a constant" like it does with | 0x8000000000000000.

I'm not sure about C++, though.

like image 69
nwellnhof Avatar answered Sep 27 '22 00:09

nwellnhof