Dynamic Allocation Basics

The questions below are due on Sunday November 15, 2026; 11:59:00 PM.
 
You are not logged in.

Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
Back to Exercises

Lecture 6 covered the topic of dynamic memory allocation which we'll be exploring on this page (which will cover the basics of malloc, realloc and free).

malloc takes in a single argument -- the number of bytes of memory we wish to allocate on the heap. It returns a pointer to the beginning of the newly allocated memory block. The newly-allocated memory will be considered taken/in use until it is explicitely freed by you as a programmer (using the free function, or by reallocating using realloc, more on that later). If malloc is unable to allocate the requested number of bytes on the heap, it will return NULL to signal the failure.

Note that malloc returns a pointer of type void *. This pointer should then be type-casted to whatever type you want it to be. If you plan on using malloc to create an array of integers, for example, you'd call malloc and cast the return pointer to type int*

Onto the first few exercises!

Basic Malloc Practice

Consider the following (successful) call to malloc:

void * ptr = malloc(256);
printf("%d\n", ptr); // prints 100
printf("%p\n", ptr); // prints 0x64

How many bytes of memory are allocated following this call to malloc?

How many memory words are allocated following this call to malloc?

What is the starting (lowest) address of the region of memory allocated by the above call to malloc? 0x

What is the ending (highest) address of the region of memory allocated by the above call to malloc? 0x

Now, consider another (successful) call to malloc:

int len = 4;
void * ptr = malloc(sizeof(uint16_t)*len);
printf("%d\n", ptr); // prints 204
printf("%p\n", ptr); // prints 0xCC

How many bytes of memory are allocated following this call to malloc?

How many memory words are allocated following this call to malloc?

What is the starting (lowest) address of the region of memory allocated by the above call to malloc? 0x

What is the ending (highest) address of the region of memory allocated by the above call to malloc? 0x

Now, consider the following code. Assume that the call to malloc was (successful):

int size = sizeof(char);
void * ptr = malloc(sizeof(uint32_t)*size);
*((char *) ptr) = 0x23;
*((char *) ptr + 1) = 0x01;
*((int16_t *) ptr + 1) = 0x6745;

printf("%d\n", ptr); // prints 1024
printf("%p\n", (void*) ptr); // prints __BLANK1__
printf("%p\n", (char*) ptr); // prints __BLANK2__
printf("%p\n", (uint32_t *) ptr); // prints __BLANK3__
printf("0x%x\n", ((uint16_t *) ptr)[0]); // prints __BLANK4__
printf("0x%x\n", ((uint16_t *) ptr)[1]); // prints __BLANK5__

How many int16_t values can fit in the allocated chunk of memory?

What gets printed for the print statement indicated by BLANK1?

What gets printed for the print statement indicated by BLANK2?

What gets printed for the print statement indicated by BLANK3?

What gets printed for the print statement indicated by BLANK4?

What gets printed for the print statement indicated by BLANK5?

Your turn. Write a function called initArr that creates a dynamically sized array of num_inp number of elements. Each element will be of the type secret_type_t. The function should return a pointer of type secret_type_t * which points the newly created array (or NULL if malloc was unable to allocate the requested number of bytes). Make sure to only allocate as much memory as is needed.

Free

Unlike stack memory which gets de-allocated when a function returns, heap memory usage persists unless explicitely freed/de-allocated, even after a function allocating the memory returns. If memory is not de-allocated properly by the user once it is done being used, the heap will eventually run out of usable memory to allocate when subsequent calls to malloc/calloc/realloc are made.

In order to free memory, one must use the free function. Calling free on a dynamically allocated pointer will return that memory chunk to the available pool.

Common mistakes surrounding free:

  1. Not freeing memory when you're done using it. Forgetting to do so is referred to as a memory leak.
  2. Double-free: Freeing memory that has already been freed.
  3. Use-after free: Attempting to de-reference or write to a memory location after it has been freed. Typically happens when using a freed pointer that has not been set to point to a new valid memory location. After the memory has been freed, the pointer is considered 'dangling' and is pointing to a region of memory that can be modified by other parts of the program. Attempting to use it can cause undefined behavior/program crashes.
  4. Freeing memory not allocated with malloc (/calloc).

For the following questions in this section, assume that free returns the allocated memory to the available memory pool immediately after the function completes and returns.

Assume the following code sequence has been run:

char * ptr_char1 = malloc(sizeof(char)*37); 
printf("%p\n", ptr_char1); // prints 0x1000
ptr_char1[2] = 0xFF;
char * ptr_char2 = malloc(sizeof(int)*10); // You can have mistmatch between sizeof type and ptr's type!
printf("%p\n", ptr_char2); // prints ???
// LOCATION 1
free(ptr_char1);
free(ptr_char2);
char * ptr_char3 = malloc(sizeof(int)*37);
ptr_char3[2] = 0x6A;
printf("%p\n", ptr_char3); // prints ???
printf("0x%x\n", ptr_char1[2]); // prints ???
// LOCATION 2

Note that the last print statement de-references a pointer (ptr_char1) after it has been freed. This is dangerous behavior and can lead to program crashes/undefined behavior. We've done it for the purpose of this exercise to make a point about dynamic memory allocation (so we'll pretend the program doesn't crash), but don't do this in practice when writing your own code.

Which of the following are potential values that ptr_char2 could have at LOCATION 1 in the program? Assume that all addresses provided below point to memory locations in the heap, and that all heap memory was available for use prior to the code above's execution.

Which of the following are potential values that ptr_char3 could have at LOCATION 2 in the program? Assume that all addresses provided below point to memory locations in the heap, and that all heap memory was available for use prior to the code above's execution.

Consider the simple function below. It attempts to copy the contents of a string stored in source a newly allocated buffer dest. The input to this function is a pointer to a dynamically allocated memory block. If the copying is successful, source is considered obsolete and should be freed by the program. If the malloc fails the contents cannot be copied over; in this case function should return NULL and preserve the contents of source, as well as its allocation status.

The freeing functionality is not implemented correctly below. Modify the function below such that it implements the same behavior as specified above but with correct freeing behavior for source.

Realloc

realloc takes in two arguments: (1) a pointer that points to a chunk of memory allocated on the heap and (2) a number input specifying the new size (in bytes) of the allocated memory being requested.

If successful, realloc returns a pointer to this newly allocated memory chunk, copies the contents over from the old memory chunk to the new memory chunk, and frees the pointer to the old memory chunk. It is possible that realloc could just resize the memory block pointed to by the initial input pointer and simply change the amount of memory allocated at that memory address: in this case, realloc would return the same pointer as was input. However, this behavior is never guaranteed, so you should write your programs assuming realloc can return a new pointer.

Realloc, like malloc, returns a pointer of type void * which must be typecast to the appropriate type (e.g char*) before being used. If realloc is unable to allocate the request size, it will return NULL and won't free the input pointer.

Good coding practice in C dicates that a user should always check if realloc, malloc, calloc, return a NULL after requesting a certain of memory allocation; this is done prevent system crashes that could come from attempting to access a NULL pointer. You may observe that we don't check for this in this exercise (and some future ones) because we'll be assuming the calls to those functions are always successful. In practice though you should check if your calls to malloc, calloc, realloc return a NULL, as we did with dynaStrCpy earlier.

Onto the exercises:

Consider the following block of code where all allocations are succesfull:

void * arr = malloc(sizeof(int)*6);

for (int i = 0; i<6; i++){
    ((int*) arr)[i] = i;
}

/*
CODE HERE
*/

We've decided we want to shrink our array arr down to the size of 3 elements and need to fill in the code in the spot indicated by CODE HERE.

For the next few subparts, assume we want to store the first 3 elements of the array arr contiguously in dynamically allocated memory. Also assume we want to de-allocate/free the memory corresponding to the last 3 elements.

Method 1:

arr = malloc(sizeof(int)*3);

Method 2:

arr = realloc(arr, sizeof(int)*3)

Method 3:

free(arr+3);

Method 4:

for (int i = 3; i<6; i++){
    arr[i] = 0;
}

Method 5:

int * arr2 = malloc(sizeof(int)*3);
for (int i = 0; i<3; i++){
    arr2[i] = arr[i];
}
free(arr);

Which of the methods above properly implement the desired functionality?

You decide to implement a new method that implements the previously described functionality in a few steps using realloc. Afterwards, you want to change the first element of the allocated array to equal 10. You would also like the variable arr to still be the one to hold the pointer to the shrunken array. How would you fill in the blanks in the code below to implement this functionality correctly?

void * arr2 = realloc(arr, sizeof(int)*3);
__BLANK1__
(__BLANK2__)[0] = 10;
__BLANK3__

How should the blanks be filled such that the added code implements the desired functionality reliably? The potential blanks will be separated by semi-colons for each of the choices below. N/A means no action should be done at the indicated blank.

Back to Exercises