ROB 502: Programming for Robotics: Class 6

Clicker Questions

Use p4r-clicker to submit your answer

1. (0b11101101 << 1) & 0x70 == 0b?
2. 0x31 ^ 0x52 == 0x?
3. char msg[] = "taco cat"; msg[3] = '\0'; printf("%s", msg);
4. printf("%ld, %ld", sizeof("hello!"), strlen("hello!"));
5. int vals[] = {5, 15, 25, 35}; printf("%ld", &vals[2] - &vals[0]);
6. int vals[] = {5, 15, 25, 35}; printf("%ld", sizeof(vals));

There is another important difference we haven’t explicitly mentioned between a declaration of

Do any of the following sections have a memory error/undefined behavior?
Either answer “N” for no, or which line (1 to 4 or whatever) of the code example will first have undefined behavior/memory errors.

7.
int vals[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 0; i < 10; i++) {
    vals[i] *= vals[i];
}

8.
char msg[] = "Walking in the park";
msg[7] = '\0';
printf("%s\n", msg);

9.
char *msg = "Walking in the park";
msg[7] = '\0';
printf("%s\n", msg);

10.
char base_msg[] = "Walking in the park";
char *msg = base_msg;
msg[7] = '\0';
printf("%s\n", msg);

11.
char *msg = malloc(strlen("Walking in the park"));
strcpy(msg, "Walking in the park");
free(msg);
msg = NULL;

12.
int *arr = malloc(sizeof(*arr) * 10);
realloc(arr, sizeof(*arr) * 20);
arr[0] = 10;
free(arr);

In-class problem 1: linked

In this problem we will implement a doubly linked list.

From the wikipedia article:

A linked list is a linear collection of data elements, whose order is not given by their physical placement in memory. Instead, each element points to the next.

As each node in a linked list is independent in memory, each one will have to be malloc’ed and freed individually. In addition, in a doubly linked list, each node not only maintains a pointer to the next node after it, but also the previous node. In implementing this data structure we have to be very careful to keep all the next and previous pointers consistent.

Each node will have three fields: next, prev, and value.
The list overall will keep track of both the start and end nodes.

We will implement the following operations, although more are possible:

  • push_start
  • push_end
  • pop_start
  • pop_end

In addition, you will also need to implement some mechanism to destroy your list, since we can’t be leaking memory!

We are providing some base code that will read the push and pop commands from a file. And whenever we pop a value off the linked list, we print it out.

For a file of commands:

push_start 1
push_start 2
pop_start
pop_start
2
1

And for:

push_start 1
push_start 2
pop_end
pop_end
1
2

And:

push_start 1
push_start 2
push_end 3
push_end 4
push_end 5
pop_start
pop_start
pop_start
pop_end
pop_end
2
1
3
5
4