Notes for Lecture 9 - February 13, 2007 ====================================== * C strings and text file conventions ** Strings *** Null character '\0' terminates string. *** strlen(s) excludes terminating null. *** sizeof s includes terminating null. ** Lines *** New line '\n' is line terminator *** fgetline() normally returns a line followed by '\n', '\0' *** Last line of file might lack '\n' ("partial line") * Segmentation faults and what causes them ** Example: int* x; char* name; FILE* in; in = fopen( name, "r" ); fscanf( in, "%i", x ); What's wrong here? *** name not initialized Doing strcpy( name, "myfile.txt" ); makes it even worse, because name doesn't point to storage. **** Solution 1 name = malloc(11); if ( name==NULL ) { ... handle error ... } strcpy( name, "myfile.txt" ); **** Solution 2 name = "myfile.txt"; *** No check made for file opening correctly If file cannot be opened, fopen() returns NULL. Must check return value. If NULL, use perror() to print error message. Attempt to use fscanf when in=NULL can cause segment fault. *** x is not initialized and doesn't point to allocated storage fscanf() likely to cause segmentation fault when storage through x or else clobber storage. *** Solution 1 x = malloc( sizeof(int) ); if ( x==NULL ) { ... handle error ... } *** Solution 2 int myint; x = &myint; * Type struct Makes a new value type that can be used like any other value -- differs from array. ** Type generator -- each use creates new type ** Use with typedef ** Tags and their uses ** Selectors: e.g., x.angle ** Pointers to structs *** Selector expression (*p).angle equivalent to p->angle. * typedef ** Defines name for a type ** Does not create a new type