-4

I have written the below code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *p=(int *)malloc(sizeof(int));
    *p=0x8F7E1A2B;
     printf("%x\n",*p);

     unsigned char *q=p;

     printf("%x\n",*q++);
     printf("%x\n",*q++);
     printf("%x\n",*q++);
     printf("%x\n",*q++);

    return 0;
}

The output of the code is as shown below:

8F7E1A2B
2B
1A
7E
8F

Can anyone please explain the output of this code. Thanks in advance.

sephiroth
  • 896
  • 12
  • 22
  • 4
    please choose either c or c++. They are two different languages. In c++ you wouldnt use `malloc` – 463035818_is_not_an_ai Dec 02 '19 at 10:33
  • 2
    Can you see a pattern? What do you think might be happening? – Sandy Dec 02 '19 at 10:34
  • 12
    Which part did you not understand? The [endianness](https://en.wikipedia.org/wiki/Endianness) of the output? – Amadeus Dec 02 '19 at 10:34
  • 3
    `malloc` is completely irrelevant; you would see the same if you wrote `int x = 0x8F7E1A2B; int* p = &x; ...` – molbdnilo Dec 02 '19 at 10:36
  • given that int's are only required to provide a much smaller range (-32767 to 32767) your code isn't portable... just saying. – UKMonkey Dec 02 '19 at 10:45
  • I was just trying to learn the use of "malloc". How the value of 'p' is stored in the command *p=0x8F7E1A2B; . since *p is of integer type so it will take just 4 bytes, Right ? The pointer variable q is incremented by just one byte, I guess as q is a character pointer. – Deepak Singh Dec 02 '19 at 11:12
  • 1
    Integers are stored in the same way no matter if you allocate them locally or on the heap. – Lundin Dec 02 '19 at 14:49

1 Answers1

2

I guess you would expect to get the bytes in Big Endian order, i.e. 8F-7E-1A-2B.

That depends entirely on the endianness of your architecture: endianness is the order of bytes in the binary representation of a number. The most common are:

  • Big Endian: the most significant byte is at the lowest address, followed by the remaining bytes in descending order. i.e. 8F-7E-1A-2B
  • Little Endian: the least significant byte is at the lowest address, followed by the remaining bytes in ascending order. i.e. 2B-1A-7E-8F. Your architecture is little endian
  • Mixed Endian: all other byte configurations that don't fall under big or little endian are possible, and they fall under the name of mixed endian. i.e. 7E-8F-2B-1A or 1A-2B-8F-7E

On a side note, you shouldn't cast the result of malloc:

int *p = (int *)malloc(sizeof(int)); // nope

int *p = malloc(sizeof(int));        // yep
sephiroth
  • 896
  • 12
  • 22