UMBC CMSC 201 Fall '06 CSEE | 201 | 201 F'06 | lectures | news | help |
Note that malloc returns a pointer value, but elements of the array can be accessed using array notation.
When we are done with the block of memory allocated by malloc we should free it using the function free.
/********************************* ** File malloc.c ** Author: S. Bogar ** Date: 3/11/04 ** Section: 01XX & 02XX ** E-Mail: bogar@cs.umbc.edu ** ** This file demonstrates memory allocation. *******************************/ #include <stdio.h> #include <stdlib.h> /*********** ** On some systems you should include the following #include <malloc.h> but it's not necessary on our system **********/ #define NUMLETTERS 26 int main() { char *letters, ch ; int i ; /* get a block of memory 26 bytes big */ letters = (char *) malloc(NUMLETTERS * sizeof(char)) ; /* make sure we actually got the memory */ if (letters == NULL) { printf("Out of memory - getting space for letters\n"); exit (-1); } /* Lets use it as an array */ i = 0 ; ch = 'a' ; while (ch <= 'z') { letters[i] = ch ; ch++ ; i++ ; } /* print out the characters */ for (i = 0 ; i < NUMLETTERS ; i++) { printf("%c", letters[i]) ; } printf("\n") ; /* Give up use of the memory block */ free(letters) ; return 0; }