Back to DFS's C Page


OAC Problem Set V

Dynamic Memory Allocation #1

These are the first of several problems which involve the use of dynamically allocated memory. For full marks, you must not only use malloc() to obtain RAM for data storage, you must also ensure that all allocated memory is freed before the program terminates. You must provide hard copy and ask the teacher to run your program.


Program I: Reading & Printing a List

Using the following compiler directive and variable declarations

#define MAXNAMES 20

char *names[MAXNAMES];
char name[80];
int numnames = 0;
int i;
FILE *fpin;
char infile[80];

write a program which will read in a list of newline-terminated strings, each of which consists of the name of a member of your class. Each name is to be stored in a separately allocated part of RAM. The newline character is not to be stored.

Your program must follow the pseudocode provided below.

  1. Open a file using a command-line argument
  2. Fill the names array with NULLs
  3. Read in names using a loop
    1. Put null char in input buffer
    2. Read in a name
    3. If EOF encountered, exit loop
    4. Delete newline if one was read in
    5. Get memory allocated
    6. Copy name into allocated memory
    7. Increment counter
  4. Close file
  5. Print out list of names with appropriate introduction
  6. Free memory used for names

N.B. A graceful exit from the program is required if the user-specified file does not exist. For this quickie program, you may assume that the memory requested is in fact allocated.


Program II: Reading, Sorting & Printing a List

Using the compiler directive and variable declarations given above for Program I, write a program which will read from a file a list of newline-terminated strings, sort them in ascending alphabetic order, print the new sorted list and write the sorted list to a file whose name is created from the name of the input file by appending .sorted, e.g. list --> list.sorted.

You can adapt any of the following sorting algorithms for your program:

Your program must follow the pseudocode provided below.

  1. Open a file using a command-line argument
  2. Fill the names array with NULLs
  3. Read in names using a loop
  4. Close file
  5. Call a function which sorts the names
  6. Call a function which prints out the list of names with appropriate introduction
  7. Call a function which writes out the list of names to a file named by appending .sorted to the end of the name of the input file
  8. Call a function which frees the memory used for names

N.B. A graceful exit from the program is required if the user-specified file does not exist. For this program, you must ensure that the memory requested is in fact allocated -- if it is not, you must call the function described in Step 8 before exiting.


Created 29 Jan 02
© DFStermole 2002