Skip to main content
Logo image

Section 21.4 Malloc and Free Practice

Time to practice! Please pick and solve at least one of the following problems:

Subsection 21.4.1 Option 1

Activity 21.1.

Write a program that does the following:
In the main function, ask the user to enter a number of integers they wish to store, and then allocate memory for a large enough array to hold all of these numbers. Next, call a function userInput(), to which you pass the array along with the size of the array, in which the user enters the desired integers which are then saved in the array. Next, your main function should call a printArray() function (to which you again pass the array and its size), and which prints out all values the user has entered.
Your main function should thus look as follows:
#include <stdio.h>
#include <stdlib.h>

/* prototypes here... */

int main (void) {
  int *numbers;
  int size;

  /* Have user enter size... */

  numbers = (int *) malloc(...); 
  userInput(size, numbers); 
  printArray(size, numbers);

  free(numbers); 
  return(0); 
}

admin.....open in new window

When you are done, please paste your code into the code submission box below:

Subsection 21.4.2 Option 2

Activity 21.2.

Write a simple C-program with a main function and a function allocateString() that allocates memory for strings. The allocateString() function should be declared as returning a pointer to a char type (namely holding the location of the string), and it takes as argument an integer, representing the number of characters to allocate space for in memory.
Your main function should call allocateString() with an argument large enough to hold the sentence “I love programming!” (don’t forget about needing space for the null terminator), and then copy this sentence into the space pointed to by the returned pointer. Next, you should print the sentence (using the pointer) and then free the pointer.

admin.....open in new window

When you are done, please paste your code into the code submission box below: