-1

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

Nikhilendra
  • 51
  • 3
  • 11
  • 3
    What makes you think it is a problem? – John3136 Jul 01 '14 at 05:45
  • What makes you think this is a problem? Have you read the documentation for `free`? – Jonathon Reinhart Jul 01 '14 at 05:45
  • Please explain why this is a problem. If you free the memory you shouldn't hang on to any pointers to it. – David Grayson Jul 01 '14 at 05:45
  • This isn't gonna work out. Virtual memory paging makes it infeasible to test system memory with a userspace application — there is no way to ensure that you're testing all memory. (Indeed, some physical memory will be wired down by the kernel, and will thus **never** be tested by your application.) –  Jul 01 '14 at 05:52
  • In operating systems with virtual memory, even if address returned by malloc is different, there is no reason to think it will be placed in different addresses in physical memory. – keltar Jul 01 '14 at 05:52

2 Answers2

4

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

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.

Community
  • 1
  • 1
Am_Sri
  • 19
  • 1
  • 3