UMBC CS 201, Spring 02
UMBC CMSC 201 Spring '02 CSEE | 201 | 201 S'02 | 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: 1/3/45 ** Section: 101 ** SSN: 123-45-6789 ** 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, c ; int i ; /* get a block of memory 26 bytes big */ letters = (char *) malloc(NUMLETTERS * sizeof(char)) ; /* Lets use it as an array */ i = 0 ; c = 'a' ; while (c <= 'z') { letters[i] = c ; c++ ; 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 S'02 | lectures | news | help

Last Modified - Wednesday, 03-Apr-2002 16:43:40 EST