开发者

memset used for memory allocation?

i was looking at this example at msdn:

http://msdn.microsoft.com/en-us/library/ms894209.aspx

DWORD dwResult;

MEMORY_BASIC_INFORMATION mbiMemory;

// Clear the results structure.
memset (&mbiMemory, 0, sizeof(MEMORY_BASIC_INFORMATION));

dwResult = VirtualQuery (lpPage,        // Page to examine
                     &mbiMemory,    // Structure for results
                     sizeof(MEMORY_BASIC_INFORMATION));

if (sizeof(MEMORY_BASIC_INFORMATION) != dwResult)
{

开发者_C百科    // Your error-handling code goes here.

}

seems like they use memset as a way to allocate memory to mbiMemory. Is it ok? wont i run over some memory this way? thanks!


No, they don't allocate memory, they just reset the struct to contain all zeroes so that it is initialized to some known state and the program behaves in reproduceable manner. Since they only overwrite that struct (sizeof is passed as "number of bytes") they won't overrun anything.


Idiomatic coding would be like this:

MEMORY_BASIC_INFORMATION mbiMemory = {0};

The problem with that is that when non-expert C++ programmers read the samples they most likely will not understand that particular syntax. Raymond Chen wrote about this recentlyway back in 2005.


No. INFORMATION mbiMemory is an automatic variable. It's a struct, and it's allocated on the stack. Just like if you'd written int foo.


The memory is allocated on the stack by this:

MEMORY_BASIC_INFORMATION mbiMemory;

the memset is clearing the memory that has been allocated to zeros.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜