The malloc function signature
What you'll learn: How to interpret the specific inputs and outputs required to request a block of raw memory from the system.
In previous lessons, we let the compiler handle memory for us by declaring variables like int x. But for dynamic allocation, we use a function called malloc (short for memory allocation). To use it effectively, you must understand its "signature"—the way it communicates with the rest of your program.
The blueprint
The signature for malloc looks like this:
void* malloc(size_t size);
At first glance, this looks a bit intimidating, but let's break it down using a simple analogy: ordering a custom-sized storage unit.
The Input: size_t size
The input, size_t size, is the only information malloc asks for. Think of size_t as a special type of integer that can never be negative; it represents a count of bytes.
If you want enough space for one integer, you don't pass the number 1. Instead, you pass the result of sizeof(int). This is like telling a warehouse manager, "I need a unit that is exactly 4 square meters," rather than just saying "I need one unit." You must be specific about the physical space required.
The Output: void*
This is the most unique part of the signature. malloc returns a void* (a void pointer).
Imagine you ask a landlord for a space to store "something." The landlord doesn't care if you are storing vintage cars, boxes of books, or grand pianos. They simply hand you a key to a room and say, "Here is the starting address of your space."
In C, a void* is that "generic key." It is a memory address that hasn't been assigned a data type yet. It points to the beginning of the block you requested, but it is up to you to tell the compiler whether that block should be treated as an array of integers, a string of characters, or something else.
Putting it into code
Here is how that signature looks when used in a real line of code:
#include <stdlib.h>
int main() {
// We ask for enough bytes to hold 5 integers
// malloc returns a void*, which we store in an int*
int *my_numbers = malloc(5 * sizeof(int));
if (my_numbers != NULL) {
// The memory is now ready to be used
}
return 0;
}
Key takeaway
The malloc function takes a specific number of bytes as an input and returns a generic pointer (void*) to the start of that newly allocated space.