C Tutorial Malloc() and Free()
The C Language
C History
BCPL
Euclid’s Algorithm in C
Euclid on the PDP-11
Pieces of C
C Types
Declarators
Struct bit-fields
Code generated by bit fields
C Unions
Layout of Records and Unions
C Storage Classes
malloc() and free()

Dynamic Storage Allocation
Simple Dynamic Storage Allocation
malloc() and free() variants
Fragmentation
Fragmentation and Handles
Automatic Garbage Collection
Arrays
Lazy Logical Operators
The Switch Statement
setjmp/longjmp: Sloppy exceptions
Nondeterminism in C

 

 

HOME
 


 

Library routines for managing the heap 

int *a;

 a = (int *) malloc(sizeof(int) * k);

a[5] = 3;

free(a); 

 

  • Allocate and free arbitrary-sized chunks of memory in any order

  • More flexible than (stacked) automatic variables

  • More costly in time and space

  • malloc() and free() use non-constant-time algorithms

  • Two-word overhead for each allocated block: Pointer to next empty block

       size of this block

 

 

 Common source of errors: 

  • Using uninitialized memor

  • Using freed memory

  • Not allocating enough  

  • Indexing past block Neglecting to free disused blocks (memory leaks)

  • Memory usage errors so pervasive, entire successful company (Pure Software) founded to sell tool to track them down 

  • Purify tool inserts code that verifies each memory access

  • Reports accesses of uninitialized memory, unallocated memory, etc.

  • Publicly-available Electric Fence tool does something similar

 

#include <stdlib.h>

struct point {int x, y; };

int play with points(int n)

{

struct point *points;

points = malloc(n*sizeof(struct point));

int i;

for ( i = 0 ; i < n ; i++ ) { points[i].x = random(); points[i].y = random();

}

/* do something with the array */ 

free(points);

 }

 

Contact for more learning: webmaster@freehost7com