Surviving C and PostgreSQL CS186 Supplemental Session 9/13/04 Matt Denny, Paul Huang, Murali Rangan (Originally prepared by Shariq Rizvi, Wei Xu, Shawn Jeffery) Outline • • • • A Review of C PostgreSQL Basics Tour of Assignment 1 2Q A Review of C • Review Pitfalls of C Programming for Java Programmers • Pointers and Arrays • Strings • Segmentation Faults • For more information, consult “ The C Programming Language” by Kernighan and Ritchie or tutorial on web site • Pointer = variable containing address of another variable float f; float *f_addr; f /* data variable */ /* pointer variable */ f_addr any float ? ? ? 4300 4304 any address f_addr = &f; /* & = address operator */ f f_addr ? 4300 4300 4304 *f_addr = 3.2; f /* indirection operator */ f_addr 3.2 4300 4300 4304 float g=*f_addr; /* indirection:g is now 3.2 */ f = 1.3; f f_addr 1.3 4300 4300 4304 Arrays and Pointers int month[12]; /* month is a pointer to base address 430: system allocates 12*sizeof(int) bytes at 430 */ month[3] = 7; /* integer at address (430+3*sizeof(int)) is now 7 */ ptr = month + 2; /* ptr points to month[2], i.e. ptr =(430+2 * sizeof(int)) = 438 */ ptr[5] = 12; /* int at address (434+5*sizeof(int)) is now 12; same as month[7] */ • Now , month[6], *(month+6), (month+4)[2], ptr[4], *(ptr+4) are all the same integer variable. Strings #include <stdio.h> main() char char char { msg[10]; /* array of 10 chars */ *p; /* pointer to a char */ msg2[]=“Hello”; /* msg2 = ‘H’’e’’l’’l’’o’’\0’ */ msg = “Bonjour”; /* ERROR. msg has a const address. Think of space allocation*/ p = “Bonjour”; /* address of “Bonjour” goes into p */ p = msg; /* OK */ p[0] = ‘H’, p[1] = ‘i’,p[2]=‘\0’; /* *p and msg are now “Hi” Warning: be careful if you have space allocated for p!!*/ } Segmentation Fault? • You reference memory that the OS doesn’t want you to • What to check? • Dereferencing a null pointer 99% – Output or trace with a debugger – Check array bounds