Archived

This topic is now archived and is closed to further replies.

Optimal

Buffers, a simple matter.

Recommended Posts

I have a small problem with buffers. I wish to set all of the buffer to the same value and in a fast and effective way. Even though this must be very easy I have failed to find any functions/methods to do so. The buffer is of the type float. ex: float *test; It''s size is set with the new function test = new float[very much]; I have check the function memset. But I don''t seem to get it to work. Thanks in advance. Optimal.

Share this post


Link to post
Share on other sites
That won''t work. What this will do is downcast the 3.14159 to 3 and then write the value 3 to the first 10 bytes (i.e. the first two and a half floats). To set them all to 3.14159, you''re going to have to use a for-loop. (Either that or write some assembly code).

Share this post


Link to post
Share on other sites
The for loop is something I have already used but it is way to slow. So any tips on where I can find some assembly code. Or some other fast solution.

Share this post


Link to post
Share on other sites
something like

void memsetf(void *dest, float val, size_t count)
{
_asm {
lea edi, [dest]
mov eax, [val]
mov ecx, [count]
rep stosd
}
}

Share this post


Link to post
Share on other sites
quote:
Original post by niyaw
something like

void memsetf(void *dest, float val, size_t count)
{
_asm {
lea edi, [dest]
mov eax, [val]
mov ecx, [count]
rep stosd
}
}



I think that lea opcode should be changed to a mov. As it is, the code will take the address of dest on the stack and try to write there.

Share this post


Link to post
Share on other sites
quote:
Original post by niyaw
no it won''t. what do you think lea does?


lea calculates the effective address and stores it in the register. Specifically lea is a arithmetic operation that calculates the address specified by the second operand as if it were to load or store data there, but instead stores the calculated address into the register specified by the first operand.

The code you have is effectively edi = &dest storing the address of the variable dest, which lies on the stack, into the edi register. So when the rep stosd is performed the stack gets overwritten.

If you don''t believe me, try it yourself. Just to double check I compiled your function in MSVC .NET and watched it corrupt the stack. Fun way to check: call your memsetf() function, as it''s written, with memsetf(NULL, 2.0f, 3) and watch it magically not cause a memory exception when the address 0 doesn''t get written to. And if you set a break point right before the function returns, you can see that dest and count both get trampled on.

Share this post


Link to post
Share on other sites