Nelson Tatius
Nelson Tatius

Reputation: 8063

Heap size and position

I'm writing my own memory allocator. If my notion is right, there is kernel's addres space from zero to 1-GB, and user-space from 1 to 4, that contains different sections like: code, stack, data, heap and others.

  1. Is it right, that heap section's size and position can't be changed during the program execution?
  2. How can I get the size and the position?
  3. All I need to do, after getting heap area, is allocate the memory at my discretion, isn't I?

Upvotes: 0

Views: 192

Answers (2)

Michael F
Michael F

Reputation: 40889

Why do you worry about this?

If you're writing an allocator a-la libc, use sbrk and/or mmap to reserve memory from the kernel. You do not need to worry about where the heap is placed with neither of those system calls.

If you want to instrument libc's malloc/calloc/realloc, things are even simpler - just wrap them in your allocator functions.

  1. Yes, the allocator effectively manages the heap by requesting memory from the kernel. Typically, as is the case with brk, its position lies after the end of the data segment, and it grows at increasing addresses (or allocates in multiples of page size with mmap, etc.)

  2. The allocator manages the size; the position of the heap is not relevant as far as the allocator is concerned, but it's at the position of knowing it.

  3. The allocator effectively requests memory from the kernel. Once it has that memory, it can distribute it to programs however it deems fit.

Upvotes: 2

Amardeep AC9MF
Amardeep AC9MF

Reputation: 19064

  1. It is an allocator which defines a heap. If you have a custom allocator, and it determines that all memory clients have returned all memory, it is perfectly valid for it to delete its heap or create a new one to supply memory requests from.

  2. Since the allocator itself defines the heap it should know its size and position. If what you are talking about is usurping the OS allocator's responsibility with your own allocator, you should only do this by using the OS allocator to obtain a block of memory then use that as the heap for your own allocator.

  3. Again, once your allocator owns the memory block it may be used at your discretion. You cannot simply take memory which is managed by another allocator and in its free pool and use it without serious potential consequences.

Upvotes: 1

Related Questions