Re: Strange code generated by compiler
- From: Tamas Demjen <tdemjen@xxxxxxxxx>
- Date: Wed, 21 Mar 2007 15:45:08 -0700
autumn48@xxxxxxxxx wrote:
why does the program randomly copy the value to be assigned, to
a register before moving it to the actual memory destination (like
when it assigns 22 to v[7], 55 to v[8] and 12 to v[10]). this doesn't
happen when using a normal c style array.
In case of a C array allocated on the stack:
int x[10];
x[0] = 22;
The compiler knows the address of the memory where the elements are located, so it can hard code it for you:
mov [esp+14h], 22
A C++ vector internally uses a C array too, but the memory is allocated dynamically (runtime) on the heap. The address of a vector object doesn't directly point to its internal array. A pointer must be dereferenced first:
vector<int> x(10);
x[0] = 22;
What happens here is that vector<T>::operator[] gets called, where an internal pointer gets dereferenced, like this:
x.internal_pointer[0] = 22;
The compiler can not hard code the address of anything allocated at runtime, it has to load it from a pointer into a register first, at least on the x86 processor family:
mov eax, [esp+14h] ; operator*: resolve pointer
mov [eax], 22 ; operator=: assign value
Try to compile the following piece of code:
int* ptr = (int*)malloc(10 * sizeof(int));
ptr[0] = 22;
ptr[1] = 55;
[...]
free(ptr);
The resulting assembly code should be very similar in nature to your vector example. In the code above, 'ptr' is not the direct address of your array, but a pointer that contains the address, so it essentially generates the same machine instructions as vector did (with physical memory offsets differring, of course).
Tom
.
- Follow-Ups:
- Re: Strange code generated by compiler
- From: Autumn
- Re: Strange code generated by compiler
- References:
- Strange code generated by compiler
- From: autumn48
- Strange code generated by compiler
- Prev by Date: Re: Service don’t start automatic with windows
- Next by Date: Re: Strange code generated by compiler
- Previous by thread: Strange code generated by compiler
- Next by thread: Re: Strange code generated by compiler
- Index(es):
Relevant Pages
|