Thread: What does Malloc do?

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    27

    What does Malloc do?

    Now I've read this thread: What does malloc() do?

    I already know from the high-level perspective what malloc does. However I want to know how an OS (Unix or Windows) interprets a malloc call.

    I'm asking this because I was looking at my process list while I was stepping through a C program and noticed that the amount of memory a process takes up doesn't change after a malloc call. The process memory only changes when I attempt to read or write to an address which I allocated with malloc.

    So from this I'm guessing the OS doesn't actually allocate virtual page entries for a process until it actually uses it (load/store ops). If this is the case then what does malloc() actually do at the low-level with the OS?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Let's make a simple program:
    Code:
    while not done
        present menu
            add item
            remove item
            show item
            exit
    There. That's our program. How could your program know how many times I choose 'add item' ahead of time? It can't. So it can't create a fixed number of pages, because there's no way to know how many times I feel like choosing 'add'.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    The pages are allocated to the process as a result of the malloc call.

    When you touch those pages, the virtual page gets mapped to some real memory.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Sep 2008
    Posts
    27
    Oh ok now I see, thanks for the reply

  5. #5

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory problem - malloc, pointers and vector
    By DrSnuggles in forum C++ Programming
    Replies: 18
    Last Post: 08-14-2009, 10:28 AM
  2. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  3. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM