5
std::cout << (DWORD)"test";

If I compile and run this I get different output values each time, but I can't figure out why.

Any ideas?

PS: I'm using Windows 7 64-bit and I'm compiling with Microsoft Visual C++ 2010 Ultimate.

Purebe
  • 147
  • 2
  • 9
  • 2
    And what were you expecting to get out of this? – R. Martinho Fernandes Sep 19 '11 at 20:17
  • It's a stupid thing to do, but a valid question- don't see justification for the downvote. – Puppy Sep 19 '11 at 20:19
  • I'm learning about determining a remote process base address, which could be something such as `"pinball.exe"` -- and to my understanding to use this with offsets (say to read the score of a game) you would use `DWORD address = (DWORD)"pinball.exe" + offset;` where `offset` could be something along the lines of `0xFC` or whatever. – Purebe Sep 19 '11 at 20:21
  • 1
    @DeadMG (if you downvote someone that is at 1 rep, and then remove the downvote, that person will be left at 3 rep. Don't tell anyone.) – R. Martinho Fernandes Sep 19 '11 at 20:25
  • `EnumProcessModulesEx()` works like a charm to find the *proper* base address of a remote process however. Figured I'd add this here in case anyone else has an absent-minded moment like me and stumbles here. – Purebe Sep 19 '11 at 20:51

2 Answers2

4

"test", in your code, is effectively a pointer to the start of the string. When you cast it to a DWORD, your casting the pointer to an integer type, and writing out that number.

As the memory location which is storing "test" can change with each run, the value you see will change.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 2
    As for *why* the address of the string constant (which comes from the executable's static data segment) changes with each run, it's probably due to [address space layout randomization](http://en.wikipedia.org/wiki/Address_space_layout_randomization) (ASLR). – Adam Rosenfield Sep 19 '11 at 20:23
2
std::cout << (DWORD)"test";

is equivalent to this:

const char *tmp = "test";
std::cout << (DWORD)tmp; 

That is, it prints the address after casting it into DWORD:

It would print the same value, if you do this also:

std::cout << (const void*)"test";
Nawaz
  • 353,942
  • 115
  • 666
  • 851