Pointers Lab
Exercise 1
a. What mistake is the following code demonstrating?
b. Write a correct swap
function for two int
s in a file swap.c
:
// compile with gcc -Wall -Werror -g -o swap swap.c
#include <stdio.h>
void swap(______ a, ________ b) {
}
int main() {
int first = 1;
int second = 2;
swap(_________, _________);
printf("first value is: %d\n", first);
return 0;
}
c. Recompile swap.c
for use with gdb (gcc -Wall -Werror -g -Og -o swap swap.c
) and explore swap
with gdb by trying out the following:
- Put a breakpoint just before going into swap (check the GDB lab if you don’t remember the commands)
- Print out the addresses of
first
andsecond
withp &first
etc - Step into
swap
and check what the values ofa
andb
are - What happens when you print the addresses of
a
andb
?
d. You can also “examine” specific locations in memory with x/ YOUR_LOCATION
. For example, my value of a
is 0x7fffffffe980
(yours may be different), and so I can see the data at that location with x/0x7fffffffe980
, which should be 1 before any swapping happens.
Exercise 2
a. Predict what the following will print:
#include <stdio.h>
int main() {
char buffer[4] = "cat";
char *ptr = buffer;
printf("What is this? %c\n", *ptr);
printf("What about this? %s\n", buffer);
return 0;
}
b. Which of the following two lines will throw an error if added to the code above and why?
*ptr = 'b';
buffer = 'b';
Exercise 3
a. Predict what the following code will output:
b. What would happen if you changed BUFFER_SIZE
to 8?
Exercise 4
What will be printed after this code runs:
Exercise 5
Copy the following into a file calculate.c
:
#include <stdio.h>
//// compile with gcc -Wall -Werror -g -o calculate calculate.c
/* Returns the sums two numbers. */
int compute_sum(int x, int y) {
return x + y;
}
/* Returns the product of two numbers. */
int compute_product(int x, int y) {
return x * y;
}
/* Function to perform calculations on input parameters x and y and set the
* sum_result and prod_result parameters to their results.
*/
void calculate(int x, int y, int *sum_result, int *prod_result) {
//TODO
}
int main(void) {
int a = 3, b = 4;
int sum, product;
//Call calculate here!
printf("sum of %d and %d is %d \n", a, b, sum);
printf("product of %d and %d is %d \n", a, b, product);
return 0;
}
Complete the calculate function and call it in main
.
Submission
You can submit your completed swap.c
and calculate.c
to the assignment on Moodle for an extra engagement credit.
Extra
If you finish the lab early, you can work on your homework and revisions.
You can also check out this blog post that has some more fun things to do with GDB to see how things are stored in memory. We’ll be doing a lot more of this in the coming weeks!