270 likes | 360 Views
Chapter Nine. Strings. Char vs String Literals. Size of data types: sizeof(“hello<br>”) 7 bytes sizeof(“hello”) 6 bytes sizeof(“X”) 2 bytes sizeof(‘x’) 1 byte Every string in C++ is an array of characters with a NULL terminator to mark the end
E N D
Chapter Nine Strings
Char vs String Literals • Size of data types: • sizeof(“hello\n”) 7 bytes • sizeof(“hello”) 6 bytes • sizeof(“X”) 2 bytes • sizeof(‘x’) 1 byte • Every string in C++ is an array of characters with a NULL terminator to mark the end • An array of characters w/o a NULL is not a string
char st3[5] will not compile: “initializer-string for array of chars is too long” - no room for \0
String I/O Functions All library functions assume your array of characters includes a NULL terminator. If not, result may be “segmentation fault, core dumped” iostream.h cout prints all characters up to \0 cin reads a word (stops at a space) into a char array, appends a \0 cin.getline reads a complete line of input into a char array, appends a \0 cin.get reads a single character, no \0
getline() Symtax getline, one of cin’s functions, uses default arguments for the length of the line to read, and the character to stop on. void cin.getline(char str[], int = 80, char = ‘\n’); dot cin’s getline function cin.getline(name,80,’\n’); read at most 80 chars stop on newline cin.getline(name, 40, ‘\t’); read at most 40 chars stop on tab
Size matters If maximum length of first name is 20 char first[21]; If maximum length of last name is 30 char last[31]; If there will be at most two spaces between first and last names: char name[53];// 20 + 2 + 30 + \0 Invalid size character array declaration is a common cause of errors and system vulnerabilities
Reminder • Strings are arrays of characters with a NULL marker or sentinel at the end • Array names are constant pointers to the element type • Other pointers can be used to access elements (offset or indices) • NULL is defined to be 0 (false)
// Whenloop finished, append NULL Slide 3 of 32
Slide 5 of 32 This final version is very similar to the strcpy() included in the C++ string library
Visiting the Library • C++ has an extensive library of string-handling functions • Every C++ string function expects a pointer to an array of characters terminated by a NULL character • Unterminated strings are a common cause of segmentation faults • Failure to check bounds is a common cause of system vulnerabilities
Slide 18 of 32 Note how much more memory is required by c4 – 80 bytes vs 16 bytes for c5 + 15 bytes for the strings stored “somewhere”
Errors char msg[5] = “Error”; // not enough space char line[80]; // for 80 char line, need 81 in array Forgetting to put NULL into string Reading beyond end of array. Often happens because library routine expects to find a NULL Buffer overflow. Writing beyond end of array char *newloc; strcpy(newloc,“Don’t try this”); // need char* but must also have a block of memory set aside