CS221: C and Systems Programming Fall 2019 - Lab 10.1
Complete the following three functions:
//Returns the second int in intArr int getSecond(void*
intArr) {
//Complete me
}
//Returns i mod 2, i is an unsigned int int mod2(int* i) {
//Complete me
}
//Returns the last character in str char theLastChar(void*
str) {
//Complete me
}
int main(void) { int intArr[5] = { 20, 4, 10, 6, 5 };
printf("The second int is %d.\n", getSecond((void*)intArr));
unsigned int i = 0xfffffff1; printf("%u mod 2 is %d.\n", i, mod2((int*)&i));
char str[] = "USF"; printf("The last character is %c.\n", theLastChar((void*)str));
}
2. Write a program “addnumbers.c” where it takes as many arguments as the user includes as command line
arguments and calculates the sum of all numbers entered, and prints it. You will find using function atoi() from
stdlib.h library helpful, where it converts the string representation of an integral number to an int value. Compile
it on a lab machine and run it using command line.
Example:
$gcc -std=c99 -o addnumbers addnumbers.c
$./addnumbers 1 4 32 56 2
95
$./addnumbers 20
20
$./addnumbers 43 2
45
3. Consider the program on the next page (malloclab.c):
(a) Draw the main memory diagram for this program. Specifically, (1) show where wordArray is stored; (2)
where is word pointing to before and after malloc; (3) what is stored in the word? (4) What happens to
wordArray after free?
(b) What happens if we add the below code after malloc? word = wordArray;
What do you expect when free function is called?
(c) What happens if we add the below code instead of the existing strcpy?
strcpy(word, wordArray[3]);
Assume that the user has entered a wordArray of length 15 (say “pointers are fun”)?
(d) What happens if we don’t free word?
(e) When does malloc return NULL?
(f) Dead objects and dangling pointers: What happens if we use word after the free call? Remember we have
freed the memory, but we are trying to access it. What should happen?
(g) Memory leaks: Say, I have a function
void runMe() { int* leakingPtr = (int*) malloc(sizeof(int) * 1024); for (int i = 0; i < 1024;
i++) { leakingPtr[i] = i + 1000;
}
}
Assume that I call runMe in the main. How does the heap look before and after the runMe call? What is
wrong in the function?
/* malloclab.c */
#include
Get Free Quote!
258 Experts Online