BasicOS
Basics
of
Operating
Systems

General information


Advanced concepts in C

This session is dedicated to the study of basic concepts of C: pointers and basic memory management.

You don't need to submit source files or reports for this session. For this session, you will need to log into a PC running Linux. If you are at Eurecom, simply log on a PC of rooms 52 or 53. If you were to use another PC running GNU/Linux, I cannot guarantee that the lab works in the same way (outputs could be different, manual pages could be different, etc.).

Trick. In Linux, do you know that you can do a copy/paste very easily with your mouse only? Simply select some text with your mouse, then move your mouse pointer to the place where you want to copy this text, and then click on the middle mouse button ... the text is copied!
This session refers to the section "Advanced Concepts in C" of the slides on . do use these slides whenever necessary.

I. Enhancing a program

  1. Save the funnyAllocation program in a directory of your choice. This program is also available in the slides.

  2. What happens if you move "free(buf)" before the last call to printf()? Test!

  3. What happens if you remove the call to "malloc..."? Try to guess what happens before testing!

  4. Modify this program such that the value of "b" defined in main() is modified by "b = b + 1" performed in funnyAllocation(). You are free to modify the program as you wish, apart from the fact that these two lines of codes ("int b" and "b = b + 1") must not be changed. Compile and test.

  5. Modify the program so that the value of the global variable "a" is not modified by funnyAllocation(). For this, you don't have the right to remove change "int a;" nor "a = 5"

II. Pointer manipulation

In this exercise, your are asked to make the following program.

Once the program has started, it must first ask the user to enter a number, for instance 5. Then, the program queries the user to enter values as many times as the first number which was entered. Thus, if the user entered "5" the first time, the program queries the user 5 times to enter a value. Once all values have been entered and stored, the program computes the sum of all values and outputs the result.

You will probably also need to use the atoi() function. Again, use the manual page to understand it.

Additional constraint: you should not use any array allocated in the stack, so use only memory allocations in the heap with "malloc()".

III. Randomness

In this exercise, your are asked to make the following program.

Generate a random value: let use call this value "size". Create a dynamic array of size "size" and fill it with random integers. Then, print the content of this array. Inverse the content of this array, and print it.

For the random number generation, we suggest using the random() function. Do read the manual page on random() first.