Recitation 6
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.
Table of Contents
1) Computing Size
(optional)1.1) sizeof Operator (optional)
Reminder that sizeof is an operator that evaluates the size of an object (variable or datatype -- you can pass either in as an input to sizeof) in bytes at compile time.
Consider the code below:
char myarr1[300];
int myarr2[100];
// LOCATION 1
int sizeCompute(int * ptr1, char * ptr2){
int size1 = sizeof(ptr1);
int size2 = sizeof(ptr2);
// LOCATION 2
return size1 + size2;
}
sizeof(myarr1) return in location 1?
sizeof(myarr2) return in location 1?
size1 at location 2 in the program? Assume we are running on a 32-bit system.
size2 at location 2 in the program? Assume we are running on a 32-bit system.
1.2) sizeof for Dynamic Mem Allocation (optional)
malloc and realloc each have an input which specifies the number of bytes to be allocated following the function call. You may notice in reading and implementing programs that the number of bytes is typically given in the following format:
chosen_type * ptr = malloc(sizeOf(chosen_type) * num_stored_vals)
or for realloc:
chosen_type * ptr = realloc(ptr, sizeOf(chosen_type) * num_stored_vals)
In these cases malloc/realloc will allocate enough bytes to store up to num_stored_vals elements, each element of which is of size sizeof(chosen_type).
When you call malloc/realloc this way, it makes it possible to determine the number of allocated bytes at runtime (for example, if num_stored_vals was a value determined by another part of our program). It also makes it easier to see how many values of a certain type could be stored at a given memory location on the heap.
If you know the number of bytes you want, say 1024, you could also just call malloc as follows:
chosen_type * ptr = malloc(1024) , allocating 1024 bytes of memory on the heap, the first byte of which is pointed to by ptr.
For the following questions: Enter the value that should be passed into the given BLANK parameter to allocate the desired number of bytes when calling malloc:
(1) We want to allocate 64 bytes in the heap:
void * ptr = malloc(__BLANK__);
void * ptr = malloc(64 * sizeof(__BLANK__));
void * ptr = malloc(32 * sizeof(__BLANK__));
(2) We want to allocate 25 words:
void * ptr = malloc(__BLANK__);
void * ptr = malloc(25 * sizeof(__BLANK__));
void * ptr = malloc(__BLANK__ * sizeof(uint8_t));
(3) We want to allocate input_len number of secret_type_t elements:
void * ptr = malloc(__BLANK1__ * sizeof(__BLANK2__));
__BLANK1__?
__BLANK2__?
2) Dynamic Memory Allocation (optional)
2.1) Calloc (optional)
The exercises for week 6 cover the mallocand realloc memory allocation functions. Here we give a quick overview of the calloc function:
calloc takes in two inputs:
- The number of elements to be allocated
- The size of each element
calloc returns:
- If successful: a non-NULL ptr to the start of the allocated memory. The number of allocated bytes will be:
sizeof(element_type)*num_elements. - NULL if the requested amount of memory cannot be allocated or if the the multiplication overflows.
However, calloc also initializes the entire allocated memory to 0.
To see some use cases where this could be beneficial, consider the block of code below. For each of the provided blanks, indicate whether both the provided malloc and calloc memory allocation calls lead to correct behavior, or if only the implementation using calloc would work.
// Initialize a string to "Make like" by copying the character manually as shown below
char source[] = "Make like";
char * dest1 = __BLANK1__
for (int i = 0; source[i]; i++){
dest1[i] = source[i];
}
// Copy the string "a tree" into dest
char * dest2 = __BLANK2__ ;
strcpy(dest2, "a tree");
// Initialize string dest3 to "and leave." using strncat
char * dest3 = __BLANK3__ ;
strcat(dest3, "and leave.");
// Copying the contents from one source int array to allocated buffer
int source_ints[5] = {1,2,0,4,5};
int * dest4 = __BLANK4__;
for (int i = 0; i<5; i++){
dest4[i] = source_ints[i];
}
// Initializing a struct pointer (of type struct randStruct *) with all pointers initialized to NULL
// Declaration: struct randStruct { int * rand1 ; int * rand2 ; char * rand3 ;};
struct randStruct * ptr2 = __BLANK5__ ;
Consider the code above (including commments explaining the intended use) and indicate whether you could place the listed malloc or calloc (or both) calls to fill the blanks and have the program work as expected.
__BLANK1__?
__BLANK2__?
__BLANK3__?
__BLANK4__?
__BLANK5__?
2.2) Good Practice
In this section we'll cover good practices to use when invoking dynamic memory allocation functions (realloc, malloc, calloc). When realloc, malloc, calloc are called, they may either return a pointer to the allocated memory segment (if the allocation was successful), or NULL if the allocation was unsuccessful (i.e, the functions could not find the request amount of memory contiguously in the heap).
You generally should not assume that the calls to these functions will be successful. In calling these functions you should therefore first check if NULL was returned before attempting to de-reference, re-use, free or generally manipulate the pointers.
Write a function memInit below that:
- Takes in two inputs:
int init_valueanduint32_t num_elements. - Attempts to allocate enough memory to store
num_elementsin the heap and initialize every value in the array toinit_value. - Returns a pointer to the allocated, initialized memory if the allocation was successful.
- Returns
NULLif the malloc was unsuccessful, and does nothing else. Hint: think about the order you do your checks in
You may assume that num_elements will always be greater than 0.
Now consider the realloc function and its behavior.
When realloc succeeds, the input pointer is freed and a valid pointer to a memory chunk of the correct size is returned. When realloc fails, NULL is returned AND the input pointer is not de-allocated.
So you should make sure that you (1) check for a NULL to see if the reallocation failed , and you should (2) make sure that you have some way of accessing the initial input pointer to realloc in case of a failure. This is because upon the failure the input pointer will still allocated, so you still want to be able to free it or use it after the failed realloc (since during failure realloc won't do this freeing for you).
Write a function resizeOrFree that, in accounting for this behavior:
- Takes in two inputs:
void * inp_ptr, the pointer to be re-sized usingrealloc, anduint32_t num_bytes, the number of bytes to be requested inrealloc. - If the reallocation fails:
resizeOrFreeshould returnNULLAND free the memory associated with the input pointer. - If the reallocation succeeds: returns the pointer to the newly sized memory chunk but does not free this newly allocated memory chunk.
2.3) All together
Having established the above facts, we can now write some more complicated functions using dynamic memory allocation.
Linked Lists
A linked list is a linear data structure consisting of a chain of nodes pointing to/linking to each other.
We'll be implementing some functionalities of a singly linked list in this recitation exercise. A singly linked list means that each node stores its data, and a pointer to the next node. If there is no node after the current one, the pointer will be NULL. A sketch of the structure is provided below.
| Head (node 0) | | node 1 | | node2 |
| Data0 | | Data1 | | Data2 |
| ptr0 -------------> | ptr1 ----------------->| ptr2---------------->NULL
Each node will be a separate instance of the struct struct Node defined below:
struct Node {
int data;
struct Node * next_node;
};
Creating the linked list
We'd like to create new nodes for our linked list at runtime and have those nodes that are created persist after a function call. This calls for dynamic memory allocation.
In the codebox below, write a function that takes an input n, creates an n-node linked list and returns a pointer to the first node in the list.
If n equals 0, the function should return NULL. The function should initialize the data for each new node to be 0.
You may assume that any call to malloc, realloc, calloc will be successful for this exercise. (We recommend that you look at the provided solution you're once done to see how we've handled the edge case of malloc returning NULL, but that is not something you should worry about here).
Modifying data in Linked List (optional)
Given a pointer to the head of a linked list, we would like to set the data at the ith node (0-indexed) to equal to the new input int new_data. This function returns the initial input pointer. You may assume that i is within range of the linked list.
Adding node to Linked List (optional)
Given a pointer to the head of a linked list, we would like to add a singular node to. The data for the added node should be inp_data. Implement the function growLL that takes in two inputs, a pointer to the linked list to grow the input data inp_data, and adds a node with the correct data to it. It then returns the input pointer. You may assume that this operation will always succeed for this exercise, and that the input will always be a non-NULL pointer.
Shrinking Linked List
Given a pointer to the head of a linked list, we would like to free the first n nodes of the list and return the new head (i.e, pointer to element n). If n is equal to 0, the current head should be returned. If n is greater than the size of the linked list, all nodes in the linked list should be freed and NULL should be returned. You may assume the input list has at least one valid node in it.
3) RISC-V Stack and Stuff
3.1) Calling Convention (optional)
Fort Xonk contains the world’s finest valuables. Its vaults are highly reputed and require maximum security. Unfortunately, a series of high-profile heists suggest that security at Fort Xonk is lacking.The management at Fort Xonk does not trust C compilers, so its security system is written entirely in RISC-V assembly. However, Fort Xonk’s programmers are not familiar with RISC-V’s calling convention, so their implementation is buggy. You’ve been hired to fix their implementation.
Each of the following questions shows a different function of the security system. Fix the assembly code so that it obeys all calling conventions. The only changes you may make are: (1) changing which registers are used for any of the instructions, and (2) pushing and popping registers to and from the stack as needed. You should minimize the number of instructions executed by your corrected code.
Note: Some of the code below uses MMIOs to interact with the outside world, as the comments describe. MMIOs are performed through loads and stores to addresses 0x40000000 or higher. You do not need to understand the MMIOs available or their behavior—the bugs in the code are with the calling convention.
# This function takes a single
# argument, an integer that
# encodes a password, and
# returns a hash of the password
hash_password:
li s1, 0x2000
slli x2, a0, 2
andi x2, x2, 0x3FF
add x2, x2, s1
lw s2, 0(x2)
xor s2, s2, a0
srli s2, s2, 8
xor t0, s2, a0
ret
3.2) Stack Detective
Below is the C code implementing two recursive functions foo and
bar that both take a single argument x. Below them is an implementation of
these functions using RISC-V assembly. Pay attention to the differences.
To help you, the differences between the functions have been marked.
| foo | bar |
|---|---|
|
|
|
|
What should be in the blanks on the lines labeled L1 and L2 to make the assembly implementation match the C code? Include the srli in your answer.
How many words will be written to the stack by the functions foo and bar?
The program’s initial call to the function foo occurs outside of the
function definition via the instruction call foo. The program is
interrupted during a recursive call to bar, just prior to the execution of
the srli instruction at label L2. The diagram below shows the
contents of a region of memory. All addresses and data values are shown
in hex. The current value in the sp register is 0xEB0 and points to the
location shown in the diagram.
| Pointers | Address | Data |
|---|---|---|
| 0xEA8 | ??? | |
| 0xEAC | ??? | |
| sp -> | 0xEB0 | 0x1 |
| 0xEB4 | 0xC4C | |
| 0xEB8 | 0x2 | |
| 0xEBC | 0xC4C | |
| 0xEC0 | 0x4 | |
| 0xEC4 | 0xC04 | |
| 0xEC8 | 0x9 | |
| 0xECC | 0xC10 | |
| 0xED0 | 0x13 | |
| 0xED4 | 0xB08 |
What are the values in the following registers right when
the execution of bar is interrupted? Write CAN’T TELL if you
cannot tell from the stack provided.
What are the hex addresses of the call foo and call bar instructions within the
functions foo and bar? Write CAN’T TELL if you cannot tell from the stack provided.
foo’s call bar instruction: 0x
foo’s call foo instruction: 0x
bar’s call bar instruction: 0x
What is the hex address of the call foo instruction that made the initial call to
foo? Write CAN’T TELL if you cannot tell from the stack provided.
foo: 0x
What was the value of the argument x at the beginning of the initial call to foo?
Write CAN’T TELL if you cannot tell from the stack provided.
4) RISC-V Assembly (optional)
4.1) Basics (optional)
Determine the values stored in the following registers when the following programs reach the unimp instruction. If you can’t tell the value from the program, write CAN’T TELL. Assume each code block is independent of the others.
start:
li a0, 0
li a1, 0xA0A0A0A0
addi a2, a0, -1
calc:
srai a1, a1, 16
xor a3, a2, a1
end:
unimp
.=0x10
f1:
li x6, 6
li x7, 0
lui x8, 2
f2:
addi x6, x6, -1
addi x7, x7, 1
bne x6, x0, f2
f3:
beqz x6, end
srai x7, x8, 12
end:
unimp
rv:
li a1, 0x2000
lw a0, 0(a1)
srli a2, a0, 12
andi a2, a2, 0x1
slli a3, a2, 12
sw a3, 4(a1)
end:
unimp
.=0x2000
.word 0x0D09F00D
.word 0x89998212
.word 0xAB19000F