So, over the course of this weekend, I will be working on my current CS project, which is implementing a version of the very important C library function, malloc. Along the way, I’ll post short updates and info dumps about malloc, and what I’m doing to implement it. To start out, I’ll give a short explanation of what malloc does, and why it’s so useful.
Malloc stands for memory allocator. Along with it’s companion function free, it is one of the fundamental functions of what is called dynamic memory.
Dynamic memory is, in its simplest form, a region of memory that can change in size and content. The basic idea is to give each program a variable ammount of space, which it can grow, shrink, and fill to fit its need. The classic example of this is a variable length array. Suppose you want build a summation program; basically, a program that can take some number of integers, add them up, and then print out the resulting sum. The obvious way to do this is to store the imputed numbers in an array, and then add them up by looping through the array. In C, it would look something like this:
int[] arr = {imput};
int length_of_arr;
int ret = 0;
int i = 0;
while(i<length_of_arr){
ret += arr[i];
}
return ret;
Now, suppose you wanted to let the user choose how many numbers they wanted to sum up. In an interpreted language like java, this would be easy; just declare a new array of whatever size the user wants, and you’re good to go. The JVM would create that array on the spot. C, however, is a compiled language. That means that any array or variable has to be declared at compile time. You can still change the value of the variable at run time, of course, but you cannot create *new* variables without dynamically allocating memory. This is where malloc comes into play. Malloc allocates, or makes available, a region of memory for use by your program. The size of that region is determined by the argument you give to malloc, which can be a variable. Malloc returns a pointer to the allocated region. Basically, the above C code becomes:
int num_imputs = {imput};
int *arr = (int *)malloc(sizeof(int)*(num_imputs));
arr[] = {imputs};
int ret = 0;
int i = 0;
while(i<length_of_arr){
ret += arr[i];
i++;
}
free(arr);
return ret;