120 likes | 219 Views
Advanced C programming. CAS CS210 Ying Ye. Boston University. Outline. C pointer GDB debugger. C pointer. Normal variable: int i = 3; 3 values related with i: size in memory: 4 address in memory: e.g. 100 (can be assigned other address) value stored in this address: 3. 0. 100. 104.
E N D
Advanced C programming CAS CS210 Ying Ye Boston University
Outline • C pointer • GDB debugger
C pointer • Normal variable: int i = 3; 3 values related with i: • size in memory: 4 • address in memory: e.g. 100 (can be assigned other address) • value stored in this address: 3 0 100 104 memory i == ? i == 3
C pointer • Pointer: int *p; • It is a variable in memory • It stores address of other variable e.g. p = &i; &: take the address of the variable Assume the address of i is 100, address of p is 50 On 32-bit machine, size of i and p: 4 and 4 0 50 54 100 104 memory p == ? p == 100 *: get the value of variable pointed by the pointer *p == ? *p == 3
C pointer • Basic operations on pointer: • assign value to pointer: p = 120; • assign value to the normal variable pointed by p: *p = 120; 0 50 54 100 104 120 124 memory 0 50 54 100 104 memory
C pointer • Practice: create a C file: vim pointer.c void add(int *x, int *y) { *x += *y; } int main(void) { int a = 1, b = 2; add(&a, &b); printf("a = %d, b = %d\n", a, b); return 0; }
C pointer • Compile: gcc -o pointer pointer.c • Run: ./pointer
GDB • wget http://cs-people.bu.edu/yingy/gdbtest.c • vim gdbtest.c • gcc -o gdbtest -ggdb gdbtest.c • ./gdbtest
GDB • Use GDB to debug it: • gdb gdbtest • run • Set breakpoint: • break 8 Breakpoint: an intentional stopping in a program, put in place for debugging purposes. Program pauses when it reaches breakpoint.
GDB int main(void) { int a[5] = {1, 2, 3, 4, 5}, b = 0; int i; for(i = 0; i <= 5; i++) b += a[i]; printf("b = %d\n", b); return 0; }
GDB • Checking variables: • run • print i • print b • continue • (jump to and repeat commands until you see i == 5)
GDB • Bug: • i == 5! • b += a[5]! • only have a[0], a[1], a[2], a[3], a[4], no a[5]! • Quit GDB: quit • Fix: for(i = 0; i < 5; i++) • Save, compile and run: • gcc -o gdbtest -ggdb gdbtest.c • ./gdbtest