cs61c_lab1
Exercise 1: See what you can C
定义常量V0,V1,V2,V3使得程序输出符合要求,同时要求四个常量中不同的值最少。
V0,V1,V3只能是3,V2取3可以满足不同的值最少。
#define V0 3
#define V1 3
#define V2 3
#define V3 3
Exercise 2: Catch those bugs!
利用gdb调试程序。任务:
- 在main函数设置断点。
- 使用gdb的run命令。
- 使用gdb的单步调试命令。
使用s会进入到printf函数中,应该用n跳过printf。
回答问题:
-
run arglist 使用run命令传入参数。
-
使用break或b在某个函数或者某一行加入断点。
-
可以使用n命令执行下一行。
-
通过s命令可以进入程序。
-
使用c命令可以继续程序。
-
可以用p打印变量。
-
使用display在程序暂停的时候打印变量
-
使用info locals 查看当前函数里的所有变量和其对应的值
-
可以使用quit或q来推出gdb
Exercise 3: Debugging w/ YOU(ser input)
我用gdb运行好像没有任何问题
Exercise 4: Valgrind’ing away
试用 Valgrind。
第一个程序会出现 Segmentation fault,第二个程序不会。
用Valgrind运行第二个程序的时候,会出现存在未初始化的变量,猜测未初始化的变量应该是数组后面的数。
Exercise 5: Pointers and Structures in C
本人代码
#include <stddef.h>
#include <stdio.h>
#include "ll_cycle.h"
int ll_has_cycle(node *head) {
/* your code here */
node *tortoise = head, *hare = head;
if (head == NULL) return 0;
while (1) {
if (hare -> next == NULL || hare -> next -> next == NULL) return 0;
hare = hare -> next -> next;
if (tortoise -> next == NULL) return 0;
tortoise = tortoise -> next;
if (tortoise == hare) return 1;
}
return 0;
}
测试脚本
gcc -c ll_cycle.c
gcc -c test_ll_cycle.c
gcc -o test_ll_cycle test_ll_cycle.o ll_cycle.o
./test_ll_cycle
echo $?