Thread: Memory allocation

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    1
    I'll bump it again. Two questions -

    Why are the calls above to malloc instead of calloc if we are making arrays? Or, does malloc return contiguous memory? My understanding is C relies on arrays being held in one chunk in memory so it can quickly jump to any index knowing only the start address and size of each element. Will malloc mess this up?

    Second - when something like "unsigned char Image[1000][1000]" is defined, is the memory in one contiguous block? Essentially, does the compiler implement it as an array of size 1000*1000, or as above (an array of pointers to arrays)? I'm wondering if allocating the data structure as above sacrificies some efficiency referencing indicies. Is it slower to pull an element out of the Image array above then one defined like "unsigned char Image[1000][1000]"?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,663
    Next time, read the rules before playing bump. I've made your post a new thread
    Reference http://cboard.cprogramming.com/showthread.php?t=43683

    > Why are the calls above to malloc instead of calloc if we are making arrays?
    calloc is simply malloc + memset
    There is no other magic involved

    > Will malloc mess this up?
    No, any single call to malloc will return a pointer to a contiguous block of memory.

    > when something like "unsigned char Image[1000][1000]" is defined, is the memory in one contiguous block?
    Yes, arrays are always contiguous

    > Essentially, does the compiler implement it as an array of size 1000*1000,
    No - that would be unsigned char Image[1000*1000]

    > or as above (an array of pointers to arrays)?
    No - that would be unsigned char *Image[1000] and lots of malloc calls

    It is an array of arrays - specifically 1000 lots of char Image[1000]

    An array of pointers is probably slower, but not by an amount which is generally worth bothering about.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory allocation question
    By dakarn in forum C Programming
    Replies: 11
    Last Post: 12-01-2008, 11:41 PM
  2. Dynamic memory allocation.
    By HAssan in forum C Programming
    Replies: 3
    Last Post: 09-07-2006, 05:04 PM
  3. Dynamic memory allocation...
    By dicorr in forum C Programming
    Replies: 1
    Last Post: 06-24-2006, 03:59 AM
  4. C memory allocation to c++
    By markucd in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2005, 05:56 AM
  5. Understanding Memory Allocation
    By Ragsdale85 in forum C Programming
    Replies: 7
    Last Post: 10-31-2005, 08:36 AM