SHARE
TWEET

Untitled

a guest Jan 24th, 2020 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Homework 0
  2. ----------
  3.  
  4. ### Watch the videos and write up your answers to the following questions
  5.  
  6. **Important!**
  7.  
  8. The virtual machine-in-your-browser and the videos you need for HW0 are here:
  9.  
  10. <http://cs-education.github.io/sys/>
  11.  
  12. Questions? Comments? Use Piazza: <https://piazza.com/illinois/spring2019/cs241>
  13.  
  14. The in-browser virtual machine runs entirely in Javascript and is fastest in Chrome. Note the VM and any code you write is reset when you reload the page, **so copy your code to a separate document.** The post-video challenges are not part of homework 0 but you learn the most by doing rather than just passively watching - so we suggest you have some fun with each end-of-video challenge.
  15.  
  16. HW0 questions are below. Please use this document to write the answers. This will be hand graded.
  17.  
  18. ### Chapter 1
  19.  
  20. In which our intrepid hero battles standard out, standard error, file descriptors and writing to files
  21.  
  22. 1.  **Hello, World! (system call style)** Write a program that uses `write()` to print out “Hi! My name is &lt;Your Name&gt;”.
  23.  
  24. ```c
  25. #include <unistd.h>
  26. int main() {
  27.     write(1,"Hello, my name is Reetahan Mukhopadhyay", 39);
  28.     return 0;
  29. }
  30. ```
  31.  
  32. 2.  **Hello, Standard Error Stream!** Write a function to print out a triangle of height `n` to standard error. Your function should have the signature `void write_triangle(int n)` and should use `write()`. The triangle should look like this, for n = 3:
  33.  
  34. ```
  35. *
  36. **
  37. ***
  38. ```
  39.  
  40. ```c
  41. void write_triangle(int n) {
  42.     int i;
  43.     int j;
  44.     for(i = 1; i <= n; i++){
  45.         for(j = 0; j < i; j++){
  46.             write(STDERR_FILENO,"*", 1);
  47.         }
  48.         write(STDERR_FILENO,"\n", 1);
  49.     }
  50. }
  51. ```
  52.  
  53. 3.  **Writing to files** Take your program from “Hello, World!” modify it write to a file called `hello_world.txt`. Make sure to to use correct flags and a correct mode for `open()` (`man 2 open` is your friend).
  54.  
  55. ```c
  56. #include <unistd.h>
  57. #include <fcntl.h>
  58. #include <sys/stat.h>
  59. #include <sys/types.h>
  60.  
  61. int main() {
  62.     mode_t mode = S_IRUSR | S_IWUSR;
  63.     int fileDescrip = open("hello_world.txt",O_CREAT | O_TRUNC | O_RDWR, mode);
  64.     write(fileDescrip,"Hello, my name is Reetahan Mukhopadhyay", 39);
  65.     close(fileDescrip);
  66.     return 0;
  67. }
  68. ```
  69.  
  70. 5. **Not everything is a system call** Take your program from “Writing to files” and replace `write()` with `printf()`. *Make sure to print to the file instead of standard out!*
  71.  
  72. ```c
  73. #include <sys/types.h>
  74. #include <sys/stat.h>
  75. #include <fcntl.h>
  76. #include <unistd.h>
  77. #include <stdio.h>
  78.  
  79. int main() {
  80.     mode_t mode = S_IRUSR | S_IWUSR;
  81.     close(1);
  82.     int fileDescrip = open("hello_world.txt",O_CREAT | O_TRUNC | O_RDWR, mode);
  83.     printf("Hello, my name is Reetahan Mukhopadhyay \n %d", fileDescrip);
  84.     close(fileDescrip);
  85.     return 0;
  86. }
  87. ```
  88.  
  89. 6.  What are some differences between `write()` and `printf()`?
  90.  
  91. Some of the differences include the fact that write() is a system call - so it is not a part of an application,
  92. but interacts with the kernel - that is designed to send bytes to a given output location. printf() is a wrapper around write()
  93. that exists in a C standard library of functions. It is more useful for formatting and more complex text to output. Since systems calls may be costly, printf() uses a buffer, so it holds the characters before making a call to write until it can hold no more or is flushed by other means,
  94. such as a new line.
  95.  
  96. ### Chapter 2
  97.  
  98. Sizing up C types and their limits, `int` and `char` arrays, and incrementing pointers
  99.  
  100. 1.  How many bits are there in a byte?
  101.  
  102.   At least 8 bits.
  103.  
  104. 2.  How many bytes are there in a `char`?
  105.  
  106. ```c
  107.   1
  108. ```
  109.  
  110. 3.  How many bytes the following are on your machine?
  111.  
  112. * `int`: 4
  113. * `double`: 8
  114. * `float`: 4
  115. * `long`: 8
  116. * `long long`: 8
  117.  
  118. 4.  On a machine with 8 byte integers, the declaration for the variable `data` is `int data[8]`. If the address of data is `0x7fbd9d40`, then what is the address of `data+2`?
  119.  
  120. ```c
  121.   0x7fbd9d50
  122. ```
  123.  
  124. 5.  What is `data[3]` equivalent to in C? Hint: what does C convert `data[3]` to before dereferencing the address? Remember, the type of a string constant `abc` is an array.
  125.  
  126. ```c
  127. data[3] is equivalent to 3[data] and *(data+3).
  128. ```
  129.  
  130. 6.  Why does this segfault?
  131.  
  132. ```c
  133. char *ptr = "hello";
  134. *ptr = 'J';
  135. ```
  136. It segfaults because "hello" is a constant - in the text segment, thus is read-only memory, thus when it attempts to edited, we have a segfault.
  137.  
  138. 7.  What does `sizeof("Hello\0World")` return?
  139.  
  140. ```c
  141. 12
  142. ```
  143.  
  144. 8.  What does `strlen("Hello\0World")` return?
  145.  
  146. ```c
  147. 5
  148. ```
  149.  
  150. 9.  Give an example of X such that `sizeof(X)` is 3.
  151.  
  152. ```c
  153. X = "ab"
  154. ```
  155.  
  156. 10. Give an example of Y such that `sizeof(Y)` might be 4 or 8 depending on the machine.
  157.  
  158. ```c
  159.   Y = int *
  160. ```
  161.  
  162. ### Chapter 3
  163.  
  164. Program arguments, environment variables, and working with character arrays (strings)
  165.  
  166. 1.  What are two ways to find the length of `argv`?
  167.  
  168.   You can either simply state the value of argc, or loop through argv, keeping a counter for each value, until you reach a null.
  169.  
  170. 2.  What does `argv[0]` represent?
  171.  
  172.   The execution name of the program.
  173.  
  174. 3.  Where are the pointers to environment variables stored (on the stack, the heap, somewhere else)?
  175.  
  176.    The pointers to environmental variables are on the stack (although these variables themselves exist in a region above
  177.      the stack.)
  178.  
  179. 4.  On a machine where pointers are 8 bytes, and with the following code:
  180.  
  181.     ``` c
  182.     char *ptr = "Hello";
  183.     char array[] = "Hello";
  184.     ```
  185.  
  186.     What are the values of `sizeof(ptr)` and `sizeof(array)`? Why?
  187.  
  188. ```c
  189. The value of `sizeof(ptr)` will be a varying value by machine but typically 8 bytes, while `sizeof(array)` will be 6 bytes.
  190. This is because `sizeof(ptr)` will tell you the size of a pointer on the machine, while `sizeof(array)` will tell you the size of needed to hold the array - the sum of each of the 5 characters, which are 1 byte each, plus 1 byte for the null character to make 6.
  191. ```
  192.  
  193. 5.  What data structure manages the lifetime of automatic variables?
  194.  
  195.     A stack.
  196.  
  197. ### Chapter 4
  198.  
  199. Heap and stack memory, and working with structs
  200.  
  201. 1.  If I want to use data after the lifetime of the function it was created in ends, where should I put it? How do I put it there?
  202.  
  203.     You should put it in the heap. You can do these by calling the malloc() function.
  204.  
  205. 2.  What are the differences between heap and stack memory?
  206.  
  207.     Heap memory starts at low address values and grows up, while stack memory starts at high addresses and grows down.
  208.     The stack is where automatic variables are placed, and when a function exits, the values of those variables may no longer
  209.     exist as the frame is taken down. However, when memory is allocated on the heap, it will exist until it is freed manually or at program exit.
  210.  
  211. 3.  Are there other kinds of memory in a process?
  212.  
  213.   A process contains stack memory, heap memory, and the data segment - which contains things like global variables and static local variables.
  214.  
  215. 4.  Fill in the blank: “In a good C program, for every malloc, there is a \_\_\_”.
  216.  
  217.     free
  218.  
  219. 5.  What is one reason `malloc` can fail?
  220.  
  221.     If it is incapable of allocating the amount of bytes requested, like when the process would be running out of (virtual) memory.
  222.  
  223. 6.  What are some differences between `time()` and `ctime()`?
  224.  
  225.     time() returns the number of seconds since 1970. ctime() returns a formatted string - a pointer to an (ASCII) character - of the current
  226.     date and time.
  227.  
  228. 7.  What is wrong with this code snippet?
  229.  
  230. ``` c
  231. free(ptr);
  232. free(ptr);
  233. ```
  234.  
  235. This is a double free. When the first free is called, the heap may use that memory for other purposes - thus, we will have undefined behavior.
  236.  
  237. 8.  What is wrong with this code snippet?
  238.  
  239. ``` c
  240. free(ptr);
  241. printf("%s\n", ptr);
  242. ```
  243. We have a freed pointer that is being called to again. As said, once the memory is freed, we shouldn't considered the memory valid as it may be being used elsewhere
  244. now in the program. Thus, we have some undefined behavior.
  245.  
  246. 9.  How can one avoid the previous two mistakes?
  247.  
  248.   Once we freed a pointer, set the pointer to be NULL.
  249.  
  250. 10. Use the following space for the next four questions
  251.  
  252. ```c
  253. #include <stdlib.h>
  254.  
  255. struct Person {
  256.     char* name;
  257.     int age;
  258.     struct Person* friends [];
  259. };
  260.  
  261. typedef struct Person person_t;
  262.  
  263. person_t* create(char* name, int age);
  264. void destroy(person_t* toDelete);
  265.  
  266.  
  267. int main() {
  268.  
  269.     person_t* agentSmith = create("Agent Smith", 128);
  270.     person_t* sonnyMoore = create("Sonny Moore", 256);
  271.  
  272.     (agentSmith->friends)[0] = sonnyMoore;
  273.     (sonnyMoore->friends)[0] = agentSmith;
  274.  
  275.     printf("Name: %s  Age: %d  Friends: %s \n", agentSmith->name, agentSmith->age, agentSmith->friends[0]->name);
  276.     printf("Name: %s  Age: %d  Friends: %s \n", sonnyMoore->name, sonnyMoore->age, sonnyMoore->friends[0]->name);
  277.     return 0;
  278. }
  279.  
  280.  
  281. person_t* create(char* name, int age){
  282.     person_t* toReturn = (person_t*) malloc(sizeof(person_t));
  283.     toReturn->name = name;
  284.     toReturn->age = age;
  285.     toReturn->friends[10];
  286.     return toReturn;
  287. }
  288.  
  289. void destroy(person_t* toDelete){
  290.     free(toDelete->name);
  291.     toDelete->name = NULL;
  292.     free(toDelete->friends);
  293.     memset(toDelete,0,sizeof(person_t));
  294.     free(toDelete);
  295.  
  296. }
  297. ```
  298.  
  299. * Create a `struct` that represents a `Person`. Then make a `typedef`, so that `struct Person` can be replaced with a single word. A person should contain the following information: their name (a string), their age (an integer), and a list of their friends (stored as a pointer to an array of pointers to `Person`s).
  300.  
  301. *  Now, make two persons on the heap, “Agent Smith” and “Sonny Moore”, who are 128 and 256 years old respectively and are friends with each other. Create functions to create and destroy a Person (Person’s and their names should live on the heap).
  302.  
  303. * `create()` should take a name and age. The name should be copied onto the heap. Use malloc to reserve sufficient memory for everyone having up to ten friends. Be sure initialize all fields (why?).
  304.  
  305. * `destroy()` should free up not only the memory of the person struct, but also free all of its attributes that are stored on the heap. Destroying one person should not destroy any others.
  306.  
  307.  
  308. ### Chapter 5
  309.  
  310. Text input and output and parsing using `getchar`, `gets`, and `getline`.
  311.  
  312. 1.  What functions can be used for getting characters from `stdin` and writing them to `stdout`?
  313.  
  314.       You can use getchar() to get characters from the stdin and putchar() to write them out to stdout.
  315.  
  316. 2.  Name one issue with `gets()`.
  317.  
  318.   If our input is larger than the size of the characters we set to read from the input (the buffer), then
  319.   we may overwrite memory being used for other things.
  320.  
  321. 3.  Write code that parses the string “Hello 5 World” and initializes 3 variables to “Hello”, 5, and “World”.
  322.  
  323. ```c
  324. #include <stdarg.h>
  325.  
  326. #include <stdio.h>
  327.  
  328. int main() {
  329.     char* data = "Hello 5 World";
  330.  
  331.     char buffer1[7];
  332.     int num = 0;
  333.     char buffer2[7];
  334.  
  335.     int result = sscanf(data, "%7s %d %7s",buffer1,&num,buffer2);
  336.     printf("Result: %d First word: %s Number: %d Second word: %s",result,buffer1,num,buffer2);
  337.     return 0;
  338. }
  339.  
  340. ```
  341.  
  342. 4.  What does one need to define before including `getline()`?
  343.  
  344.   ```C
  345.   #define _GNU_SOURCE
  346.   ```
  347. 5.  Write a C program to print out the content of a file line-by-line using `getline()`.
  348.  
  349. ```c
  350. #include <stdio.h>
  351. #define _GNU_SOURCE
  352. #include <stdlib.h>
  353.  
  354. int main() {
  355.  
  356.     FILE* tempFile = fopen("example.txt","r");
  357.     char* buffer = NULL;
  358.     size_t capacity = -42;
  359.  
  360.     while(getline(&buffer,&capacity,tempFile) != -1){
  361.         printf("%s",buffer);
  362.     }
  363.  
  364.     fclose(tempFile);
  365.     free(buffer);
  366.     return 0;
  367. }
  368.  
  369. ```
  370.  
  371. ### C Development
  372.  
  373. These are general tips for compiling and developing using a compiler and git. Some web searches will be useful here
  374.  
  375.  
  376. 1.  What compiler flag is used to generate a debug build?
  377.  
  378.   The "-g" flag.
  379.  
  380. 2.  You fix a problem in the Makefile and type `make` again. Explain why this may be insufficient to generate a new build.
  381.  
  382.   If you just type 'make' it may only rebuild the updated files and not rebuild any files that were already built.
  383.  
  384. 3.  Are tabs or spaces used to indent the commands after the rule in a Makefile?
  385.  
  386.   Tabs.
  387.  
  388. 4.  What does `git commit` do? What’s a `sha` in the context of git?
  389.  
  390.     "git commit" will save the current directory's state (changes) to its git repository, with a message. A 'sha', known as
  391.     a 'SHA-1' is a checksum hash that tags every commit (it's a hash of some metadata with the commit), that should act as an
  392.     identifier.
  393.  
  394. 5.  What does `git log` show you?
  395.  
  396.   It shows the history of commits.
  397.  
  398. 6.  What does `git status` tell you and how would the contents of `.gitignore` change its output?
  399.  
  400.  "git status" tells you the state of the current repository - like what files/folders are/aren't being tracked by Git,
  401.  and what files/folders are/aren't staged for a commit. A ".gitignore" file would give the types of untracked files that
  402.   "git status" would not list as untracked, as the user intentionally wants them to be ignored.
  403.  
  404. 7.  What does `git push` do? Why is it not just sufficient to commit with `git commit -m ’fixed all bugs’ `?
  405.  
  406.   "git push" will push all the changes committed in the local repository to the remote repository. Just committing changes
  407.   will not make a change on the remote repository.
  408.  
  409. 8.  What does a non-fast-forward error `git push` reject mean? What is the most common way of dealing with this?
  410.  
  411.   It means Git cannot push the changes to the remote repository without losing other commits. The remedy is to pull
  412.   the current state of the branch and to repair any conflicts before pushing again.
  413.  
  414. ### Optional: Just for fun
  415.  
  416. -   Convert your a song lyrics into System Programming and C code covered in this wiki book and share on Piazza.
  417.  
  418. -   Find, in your opinion, the best and worst C code on the web and post the link to Piazza.
  419.  
  420. -   Write a short C program with a deliberate subtle C bug and post it on Piazza to see if others can spot your bug.
  421.  
  422. -   Do you have any cool/disastrous system programming bugs you’ve heard about? Feel free to share with your peers and the course staff on piazza.
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top