The malloc() Call

This lesson teaches you the `malloc` call with the help of some examples.

We'll cover the following

The malloc() call is quite simple: you pass it a size asking for some room on the heap, and it either succeeds and gives you back a pointer to the newly-allocated space, or fails and returns NULL​.

man malloc

The manual page shows what you need to do to use malloc; type man malloc at the command line in the terminal provided below and you will see:

#include <stdlib.h>
  ...
  void *malloc(size_t size);

Terminal 1
Terminal
Loading...

From this information, you can see that all you need to do is include the header file stdlib.h to use malloc. In fact, you don’t really need to even do this, as the C library, which all C programs link with by default, has the code for malloc() inside of it; adding the header just lets the compiler check whether you are calling malloc() correctly (e.g., passing the right number of arguments to it, of the right type).

Specifying space needed

The single parameter malloc() takes is of type size_t which simply describes how many bytes you need. However, most programmers do not type in a number here directly (such as 10); indeed, it would be considered poor form to do so. Instead, various routines and macros are utilized. For example, to allocate space for a double-precision floating point value, you simply do this:

 double *d = (double *) malloc(sizeof(double));

Let’s try out the above instructions in the widget below:

Press + to interact
#include<stdio.h>
int main() {
double *d = (double *) malloc(sizeof(double));
printf("%d\n", sizeof(d));
return 0;
}

Wow, that’s a lot of double-ing! This invocation of malloc() uses the sizeof() operator to request the right amount of space; in C, this is generally thought of as a compile-time operator, meaning that the actual size is known at compile time and thus a number (in this case, 8, for a double) is substituted as the argument to malloc(). For this reason, sizeof() is correctly thought of as an operator and not a function call (a function call would take place at run time).

TIP: WHEN IN DOUBT, TRY IT OUT

If you aren’t sure how some routine or operator you are using behaves, there is no substitute for simply trying it out and making sure it behaves as you expect. While reading the manual pages or other documentation is useful, how it works in practice is what matters. Write some code and test it in the widget provided below! That is no doubt the best way to make sure your code behaves as you desire. Indeed, that is what we did to double-check the things we were saying about sizeof() were actually true!

Press + to interact
#include<stdio.h>
int main() {
printf("hello, world\n");
return 0;
}

You can also pass in the name of a variable (and not just a type) to sizeof(), but in some cases,​ you may not get the desired results, so be careful. For example, let’s look at the following code snippet (lines 4-5):

Press + to interact
#include<stdio.h>
int main() {
int *x = malloc(10 * sizeof(int));
printf("%d\n", sizeof(x));
return 0;
}

On line 4, we’ve declared space for an array of 10 integers, which is fine and dandy. However, when we use sizeof() in the next line, it returns a small value, such as 4 (on 32-bit machines) or 8 (on 64-bit machines). The reason is that in this case, sizeof() thinks we are simply asking how big a pointer to an integer is, not how much memory we have dynamically allocated. However, sometimes sizeof() does work as you might expect. Let’s check out the code in the widget below:

Press + to interact
#include<stdio.h>
int main() {
int x[10];
printf("%d\n", sizeof(x));
return 0;
}

In this case, there is enough static information for the compiler to know that 40 bytes have been allocated.

Another place to be careful is with strings. When declaring space for a string, use the following idiom: malloc(strlen(s) + 1), which gets the length of the string using the function strlen(), and adds 1 to it in order to make room for the end-of-string character. Using sizeof() may lead to trouble here.

Cast

You might also notice that malloc() returns a pointer to type void. Doing so is just the way in C to pass back an address and let the programmer decide what to do with it. The programmer further helps out by using what is called a cast; in our example above, the programmer casts the return type of malloc() to a pointer to a double. Casting doesn’t really accomplish anything, other than tell the compiler and other programmers who might be reading your code: “yeah, I know what I’m doing.” By casting the result of malloc(), the programmer is just giving some reassurance; the cast is not needed for the correctness.

Get hands-on with 1400+ tech skills courses.