Are address offsets resolved during compile time in C/C++? [closed]

人盡茶涼 提交于 2019-12-14 03:33:49

问题


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?


回答1:


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));



回答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


来源:https://stackoverflow.com/questions/11491191/are-address-offsets-resolved-during-compile-time-in-c-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!