1

When I execute the program I expect the address to be 0xffc10004:

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

int main()
{
    uint32_t *a = (uint32_t *)0xFFC10004;
    printf("%p\n",(a+ 0x40));
    return 0;
}

But the result I get is 0xFFC10104

When I replace 0x40 with 0x10 I get the expected address 0xffc10004. Can anyone explain the reason?

Joel Bodenmann
  • 1,776
  • 2
  • 11
  • 29
Rani Nivas
  • 11
  • 1
  • _Hi When I execute the program I expect the address to be 0Xffc10004_. I expect that you mean _Hi When I execute the program I expect the address to be 0Xffc10008_? (i.e. `0Xffc10004 + sizeof(uint32_t) == 0Xffc10008` – ryyker Aug 07 '20 at 21:58

2 Answers2

1

Since a is a pointer to uint32_t, a+0x40 points to a location which stands 0x40 uint32_t (0x100 bytes) after a, not 0x40 bytes after the address stored in a.

Pointer arithmetic takes in consideration the size of the elements a pointer is supposed to point at.

Imagine a actually points to a uint32_t inside an array; if a+2 didn't consider the whole elements but the bytes, then this would lead to designating half the previous integer and half the next! Fortunately this is not the case because it actually designates another integer situated two elements (eight bytes here) further.

If you actually want to count individual bytes, you should use a pointer to uint8_t (or char).

prog-fh
  • 7,550
  • 1
  • 3
  • 21
1

In your post you state: When I execute the program I expect the address to be 0Xffc10004

But then you start off with:

uint32_t *a = (uint32_t *)0xFFC10004;

Did you mean uint32_t *a = (uint32_t *)0xFFC10000; ?

Based on the assumption of a typo in your code segment the following will use (uint32_t *)0xFFC10000.

But first Keep in mind that the value 0x40 is not the same as 0x4

    0x40; == 64
    0x4;  == 4 (use this one if you want to see a 4 byte change) 

When incrementing a pointer type, the distance from one location to the next sequential location is always sizeof(type). For example:

a + 1 == a + sizeof(uint32_t)
a + 0x40 == a + 0x40*sizeof(uint32_t)

etc.

This will illustrate:

uint32_t *p = (uint32_t *)0xFFC10000;//starting with value intended in post (not 0xFFC10000)
printf("base location: \t\t%p\n", p);    // base location of p
printf("base location + 0x4:\t%p\t(%p + 0x4*sizeof(uint32_t))\n", p+0x4, p);    // adds 4*sizeof(uint32_t) to base location  of p
printf("base location + 0x40:\t%p\t(%p + 0x40*sizeof(uint32_t))\n", p+0x40, p); // adds 0x40*sizeof(uint32_t) to base location  of p
printf("base location + 1:\t%p\t(%p + sizeof(uint32_t))\n", p+0x1, p);          // adds 1*sizeof(uint32_t) to base location of p

Outputs the values as indicated above:

enter image description here

ryyker
  • 20,437
  • 3
  • 35
  • 78