1 / 12

Advanced C programming

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.

moana
Download Presentation

Advanced C programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced C programming CAS CS210 Ying Ye Boston University

  2. Outline • C pointer • GDB debugger

  3. 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

  4. 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

  5. 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

  6. 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; }

  7. C pointer • Compile: gcc -o pointer pointer.c • Run: ./pointer

  8. GDB • wget http://cs-people.bu.edu/yingy/gdbtest.c • vim gdbtest.c • gcc -o gdbtest -ggdb gdbtest.c • ./gdbtest

  9. 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.

  10. 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; }

  11. GDB • Checking variables: • run • print i • print b • continue • (jump to  and repeat commands until you see i == 5)

  12. 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

More Related