-1
void *p = malloc(1000);
*((int*)p) = 666;
*((int*)p+sizeof(int)) = 777;
int i;
for (i = 0; i<10; ++i)
    printf("%d ", *((int*)p+sizeof(int)*i));

Is the manual offset being resolved at compile time or does it add overhead of performing arithmetic operations during runtime?

dtech
  • 47,916
  • 17
  • 112
  • 190
  • 4
    Why don't you look at the assembly produced and judge for yourself? It's not clear what offset you're talking about, and it will possibly depend on your compiler and optimization settings. – Mat Jul 15 '12 at 10:35
  • I am talking about the offset from the address of the p pointer. – dtech Jul 15 '12 at 10:37
  • 2
    There's three of those, one inside a loop. And my comment above applies: check what your compiler produces. – Mat Jul 15 '12 at 10:38
  • 2
    That is some pretty monstrous code... – jalf Jul 15 '12 at 10:39
  • @Mat - I deliberately put 3 different scenarios to make a point. I am not very good at reading assembly, that is why I asked here. – dtech Jul 15 '12 at 10:42
  • What compiler for what platform with what optimization settings? I claim too localized. – RedX Jul 15 '12 at 11:14

2 Answers2

3

Even if you have a constant instead of sizeof(int), compiler cannot know in advance the address in p, so it will have to do the addition. If you have something like i = sizeof(int)+4 then it should do the optimization compile time and directly set i to 8.

Also, I think when you do:

*((int*)p+sizeof(int)) = 777;

what you mean is:

*((int*)p + 1) = 777; /* or ((int*)p)[1] = 777; */

similarly printf("%d ", *((int*)p+sizeof(int)*i)); should be:

printf("%d ", *((int*)p + i));
perreal
  • 94,503
  • 21
  • 155
  • 181
2

sizeof(int) is definitely known at compile time and it makes all sense to make efficient use of this information. There's no guarantee, however, that a given compiler will generate something like this:

mov dword [ebx+16], 777

instead of something like this:

mov ecx, 16
mov dword [ebx+ecx], 777

or

lea ebx, [ebx+16]
mov dword [ebx], 777

or even

add ebx, 16
mov dword [ebx], 777
Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180