Memory allocated not used unless initialized?

前端 未结 2 1661
无人共我
无人共我 2021-01-27 03:23

This is a followup to the question I just asked here.

I\'ve created a simple program to help myself understand memory allocation, malloc() and free()<

相关标签:
2条回答
  • 2021-01-27 03:48

    it could be compiler optimization : the memory is not used at all, so a possible optimization is to not allocate this memory depening on compiler and on optimization options.

    i tested your code, the line : free((void *)pmeg); does not cause any memory leak for me.

    0 讨论(0)
  • 2021-01-27 03:57

    Allocated memory can be in two states in Windows: Reserved, and Commited (see the documentation of VirtualAlloc about MEM_RESERVE: "Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging file on disk.").

    If you allocate memory but do not use it, it remains in the Reserved state, and the OS doesn't count that as used memory. When you try to use it (whether it is only on write, or on both read and write, I do not know, you might want to do a test to find out), it turns into Commited memory, and the OS counts it as used.

    Also, the memory allocated by malloc will not be full of 0's (actually it may happen to be, but it's not guaranteed), because you have not initialised it.

    0 讨论(0)
提交回复
热议问题