Complete the following function to clear a block of memory (initialize all the bits to zero). The block of memory starts at pStartByte, and is numBytes long.
void clearMemory(void *pStartByte, int numBytes)
{
{
Complete the following function to clear a block of memory (initialize all the bits to zero). The block of memory starts at pStartByte, and is numBytes long.
3 Comments so far
Leave a comment
void clearMemory(void *pStartByte, int numBytes) {
if (pStartByte == NULL) {
return;
}
char* buffer = (char*)pStartByte;
while (numBytes–) {
*buffer++ = ”;
}
}
By kiklop on 12.30.06 10:59 am | Permalink
Depending on the objective the first solution listed above can be improved. The first solution does a memory access for every byte of memory being initializes. However most modern CPUs (80286 and higher for Intel) can access memory at 32 bits or more. So why waste cycles hitting memory by bytes…
void ClearMemory(void* pStartMem, int numBytes)
{
unsigned long *plMem = (unsigned long *)pStartMem;
unsigned char *pcMem = (unsigned char *)pStartMem;
if (pStartMem == NULL)
return;
while(numBytes > sizeof(unsigned long))
{
*plMem++ = 0;
numBytes -= sizeof(unsigned long);
}
pcMem = (unsigned char *)plMem;
while(numBytes–)
{
*pcMem++ = 0;
}
}
By Rodneyk on 02.04.08 12:26 pm | Permalink
Why wouldn’t you just do this –
void clearMemory(void *pStartByte, int numBytes)
{
while ( numBytes– ) *((char*)pStartBytes) = 0;
}
By Nix on 09.29.09 1:05 pm | Permalink
Leave a comment
If you are including code in your comment, place it within a <div class='code'></div> tag for better formatting.