UMBC CS 201, Fall 06
UMBC CMSC 201
Fall '06

CSEE | 201 | 201 F'06 | lectures | news | help

Allocating memory with malloc()

This program uses malloc to allocate the space needed to hold an array of 26 characters, which we will use to store the letters of the alphabet.

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.

The Program

/********************************* ** 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; }

The Sample Run

abcdefghijklmnopqrstuvwxyz


CSEE | 201 | 201 F'06 | lectures | news | help

Last Modified - Tuesday, 22-Aug-2006 07:14:10 EDT