Exception for Custom Memset function with Large array to set value.

  • Thread starter Thread starter Harsha_MR
  • Start date Start date
H

Harsha_MR

Guest
I have written a custom Memset function instead of using the one provided by compiler itself. I'm don't see any issue when initializing an array with smaller length but while initializing for larger array length (say 5000000), I do get an exception for access violation.


"Exception thrown: write access violation. Ddest_p was 0x4DA4E112."

I have 2 design made for this custom memset but in both the case I do get the same exception at the same place when initializing for larger array.

If I use compiler provided API, I don't see any exception. So, not sure how this access violation exception is showing up only with these design.

Array gets initialized to some extent and then in a middle this exceptions comes.




void* memset(void* p_ptr_p, signed short p_value, unsigned long long int p_num)
{
//Logic 1:
uInt32 Dvalue = static_cast<uInt32>((static_cast<Byte>(p_value)) & MASK_EIGHT_BIT);
Dvalue = Dvalue | (Dvalue << EIGHT_VALUE);
Dvalue = Dvalue | (Dvalue << SIXTEEN_VALUE);
// Compute total # of DWORDs to copy.
register uInt64 numDwords = static_cast<uInt64>(p_num >> 2);
register uInt32* Ddest_p = static_cast<uInt32*> (p_ptr_p);
for (uInt64 d = static_cast<uInt64>(0); d < numDwords; d++)
Ddest_p[d] = Dvalue; // Do get exception for larger value of p_num

// now copy any left over odd (smaller than DWORD) # of bytes.
register Byte* Bdest_p = reinterpret_cast<Byte*> (&Ddest_p[numDwords]);
register uInt32 numBytes = static_cast<uInt32>(p_num & MASK_BYTES_LEFT_WORD);
for (uInt32 i = static_cast<uInt32>(0); i < numBytes; i++)
Bdest_p = static_cast<Byte>(p_value);

return p_ptr_p;

//Logic 2:
//Check if the total number of bytes are atleast 8bytes to do 64-bit memset.
//64-bit memset is performed only when the both Destination Memory addresses
//are 64-bit memory aligned and any remaining bytes after 64-bit will be
//set with 32-bit or 8-bit logic.
if (TotalnumBytes >= 8)
{
// Bit wise AND operation performed on Destination Memory address with value (0x07) to check
// if both the addresses are 64-bit memory aligned.
// Last 3-bits of the addresses decide if memory is 64-bit aligned or not.
if (!((*((uInt64*)(&Ddest_p))) & uInt64(0x07)))
{
uInt64 Dvalue = p_value;
Dvalue = Dvalue | (Dvalue << 8);
Dvalue = Dvalue | (Dvalue << 16);
Dvalue = Dvalue | (Dvalue << 32);
while (TotalnumBytes >= 8)
{
*Ddest_p++ = Dvalue; // Do get exception for larger value of p_num
TotalnumBytes -= 8;
}
}

Continue reading...
 
Back
Top