0

I'm trying to convert an address to its equivalent in Little-Endians using the following code :

void AddressToLittleEndian(UINT32* adr, UINT32 value) { *adr = value; }


int main()
{
    char *ptr = (char*) 0x41424344;
    char Adr[4];
    AddressToLittleEndian((UINT32*)Adr, (UINT32)ptr);
    cout << Adr;
    _getch();
    return 0;
}

It works without error but gives me the following result :

DCBA╠╠╠╠╠╠╠╠DCBA╠╠╠╠<,ö∩╨≈Å

The desired result is DCBA and I can somehow substring the first 4 character but actually I'm curious to know why this happens? It seems the junk code comes from the stack but I wonder what's wrong with this code that causes the stack leak ?

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
Migo Lopak
  • 29
  • 6
  • You char array is not a '\0' terminated string. Why should it print like one? –  Feb 08 '18 at 10:55
  • You didn't convert here, you just use local endianess. – Jarod42 Feb 08 '18 at 11:03
  • 1
    I tried counting UBs, but I miss a few fingers. You cannot cast pointers to integer types. You'll find help in the `htoxxx()` function manuals. – YSC Feb 08 '18 at 11:07
  • https://stackoverflow.com/questions/105252/how-do-i-convert-between-big-endian-and-little-endian-values-in-c – Component 10 Feb 08 '18 at 11:25
  • What's the use case for changing the endianness of a pointer? You can't exactly send it to a different computer anyway. – Bo Persson Feb 08 '18 at 11:34

1 Answers1

0

I don't think there is an operator which takes a char array and sends it to cout. So Adr decays to a pointer to char which, when displayed, requires a zero value as the last character. A zero character can just be 0 or '\0'. It symbolises the end of string.

Change the code to:

char Adr[5];
AddressToLittleEndian((UINT32*)Adr, (UINT32)ptr);
Adr[4] = 0;
cout << Adr;

That should not display the "junk".

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31