简体   繁体   中英

Malloc allocating same block of memory

I used C library malloc to allocate 8MB memory, after using that memory I used free to free the 8MB memory.

But when i used malloc again to allocate 8MB of memory, it is allocating the same location as allocated previously.

How to avoid this problem and why does this occur?

EDIT: I'm implementing a tool to test main memory, if malloc allocates the same block of memory it is not possible to check the whole memory

This is not a problem per se, and is by design. Typical implementations of malloc will recycle blocks of memory for reasons of performance. In any case, since malloc returns addresses from a limited pool of values, there's no way it could guarantee not to recycle blocks.

The only sure fire way to stop malloc returning blocks that is has returned before is to stop freeing them. Of course, that's not really very practical.

I'm implementing a tool to test main memory. If malloc allocates the same block of memory it is not possible to check the whole memory.

Your tool to test main memory cannot be implemented with malloc, or indeed by any user mode program. Modern operating systems don't give you access to physical memory. Rather they present a virtualized view of memory. The addresses in your program are not physical addresses, they are virtual address. Testing physical memory requires you to go in at a much lower level than is possible from a user mode program.

This should help you How malloc works? To prevent this, allocate a few bytes using malloc/calloc and then free the bigger chunk of memory. BTW this is not a wrong behavior to get the same memory address.

You might want to call system() to run a few linux commands (that provide detailed memory mgmt options) from your code.Main memory management cannot be done/tested using malloc/free, they are limited to operating on the memory allocated to your program when it is running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM