How to Free Memory with the malloc() Function in C Programming - dummies

How to Free Memory with the malloc() Function in C Programming

By Dan Gookin

Here’s a secret: Declaring a variable in C programming is in reality directing the program to beg for some storage space from the operating system. As you know (hopefully, you know), the operating system is the Lord High Master of the computer or whatever electronic device you’re programming. As such, it doles out RAM to programs that request it.

When you declare a variable, from a lowly short int to a massive string buffer, you’re directing the program to beg for that much space, into which you plan to put something useful. In the C language, you can also allocate memory on the fly, as long as you have an army of pointers at hand to save the addresses.

Basics of the malloc() function

The malloc() function exists to sate your program’s memory cravings. Give it a pointer, and malloc() allocates memory (get it?) in a given size to store a certain variable type. Here’s the format:

p = (type *)malloc(size);

type is a typecast, directing malloc() to allocate a chunk of memory sized to store the proper amount of information for the given variable type.

size is the quantity of storage that’s needed. It’s measured in bytes, but you must be careful to allocate enough storage to accommodate the variable type. For example, if you need space to store an int value, you need to create enough storage space into which an int value fits. That number of bytes is traditionally calculated by using the sizeof operator.

The malloc() function returns the address of the chunk of memory that’s allocated. The address is stored in pointer p, which must match the variable type. When memory can’t be allocated, a NULL value is returned.

You must check for the NULL before you use the allocated memory! If you don’t, your program will meet with certain peril.

Finally, you need to include the stdlib.h header file in your source code to keep the compiler pleased with the malloc() function. Give Me Space shows an example.


#include <stdio.h>
#include <stdlib.h>
int main()
 int *age;
 age = (int *)malloc(sizeof(int)*1);
 if(age == NULL)
 puts("Unable to allocate memory");
 printf("How old are you? ");
 printf("You are %d years old.n",*age);

The first thing to notice about Give Me Space is that the only variable declared is a pointer, age. An int variable isn’t defined, even though the program accepts int input and displays int output.

Line 8 uses malloc() to set aside storage for one integer. To ensure that the proper amount of storage is allocated, the sizeof operator is used. To allocate space for one integer, the value 1 is multiplied by the result of the sizeof(int) operation. (That process is unnecessary at this point, but it comes into play later.) The address of that storage is saved in the age pointer.

Line 9 tests to ensure that malloc() was able to allocate memory. If not, the value returned is NULL (which is a constant defined in stdlib.h), and the program displays an error message (refer to Line 11) and quits (refer to Line 12).

You’ll notice that the scanf() function at Line 15 doesn’t use the & prefix. That’s because the age variable is a memory address — it’s a pointer! You don’t need the & in that case (just as you don’t need the & for a string read by the scanf() function).

Finally, peeker notation is used in Line 16 to display the value input.

Exercise 1: Fire up a new project using the source code from Give Me Space. Build and run.

Exercise 2: Using Give Me Space as your inspiration, write a program that asks for the current temperature outside as a floating-point value. Have the code ask whether the input is Celsius or Fahrenheit. Use malloc() to create storage for the value input. Display the resulting temperature in Kelvin. Here are the formulae:

kelvin = celsius + 273.15;
kelvin = (fahrenheit + 459.67) * (5.0/9.0);

Exercise 3: Write a program that allocates space for three int values — an array. You need to use only one malloc() function to accomplish this task. Assign 100, 200, and 300 to each int, and then display all three values.

How to create string storage

The malloc() function is commonly used to create an input buffer. This technique avoids declaring and sizing an empty array. For example, the notation

char input[64];

can be replaced by this statement:

char *input;

The size of the buffer is established inside the code by using the malloc() function .In Allocating an Input Buffer, the malloc() function at Line 8 declares a char array — a storage buffer — for about 1,024 bytes. Okay, it’s a kilobyte (KB).


#include <stdio.h>
#include <stdlib.h>
int main()
char *input;
input = (char *)malloc(sizeof(char)*1024);
puts("Unable to allocate buffer! Oh no!");
puts("Type something long and boring:");
puts("You wrote:");