Monday, February 14, 2011

Using malloc(), realloc(), free() in C


Malloc is a subrouitine for performing dynamic memory allocation in C and C++.
  • must be freed by free()
  • memory is uninitialized
  • not guaranteed to succeed.  Return NULL if fails.

C manages memory statically, automatically, or dynamically.

static-duration variables are allocated in main (fixed) memory and persist for the lifetime of the program.

automatic-duration variables are allocated on the stack and come and go as function are called and return.  Size of allocation is required a compile time (a compile-time constant).

dynamic-duration variables are allocated on the heap in C using malloc.
  • use free(ptr) free pointer and returns memory to heap.

dynamic memory allocation (also known as heap-based memory allocation) is the allocation of memory storage in a computer program during runtime.


heap overflow 
  • a buffer overflow that occurs in the heap data area
  • typically contains program data

stack-based memory allocation
  • a computing architecture where regions of memory have data added or removed in a list-in-first-out manner
  • each threat usually has its own stack
  • typically faster than heap-based memory allocation
  • programmer doesn't need to release the memory used.
  • memory size for a given threat is small (a few dozen kilobytes)

http://publications.gbdirect.co.uk/c_book/chapter5/sizeof_and_malloc.html

Has some nice examples.

sizeof(char) is always 1.

malloc(10) // allocates ten chars.

malloc(sizeof(int[10])) // allocates ten ints

If malloc cannot find enough space to satisfy the request, a null pointer is returned.

There is a lot more here on malloc, but that is beyond what I need at the moment.  However, I may need to use there GROW_BY approach to allocating more memory.


calloc()
  • initializes memory block to 0.
  • parameter are element count and size of each element.
  • should be slower than malloc()

realloc()
  • data is unchanged
  • new memory is unallocated
  • if new size is smaller than old size, memory is truncated.
  • if new returned pointer is set to original pointer, could get a memory if a NULL is returned.

No comments: