Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
C-Style Strings
Mike Closson
Dept of Computing ScienceUniversity of Alberta
Small modifications: Michael Buro Feb.2006
22nd February 2006
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Introduction to printf, fprintf.
Printing Strings:
/* Print to standard output */printf( "Hello, World!\n" );
/* Print to file associated with filepointer fp */fprintf( fp, "Hello, World!\n" );
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Flushing an I/O stream with fflush.
For performance reasons, data written with the stream functions(fwrite, printf, fprintf) may not always appear on theterminal or file after the printf function returns. To force thedata to be written, use the fflush function.
printf("Enter your password: ");fflush( stdout );
Usually, fflush is not needed.
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Reading data with scanf.
Data is written with printf, and data is read with scanf.
char password[100];
printf( "Enter your password: " ); fflush( stdout );if (scanf( "%99s", password ) != 1) // Error ...
Note that we asked scanf to read at most 99 characters, thisprevents a potential buffer overflow.
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Reading integers and doubles with scanf.
The scanf family of functions can also be used to read integersand doubles. The number of successfully read data items isreturned.
int i;double d;
if (scanf( "%d", &i ) != 1) // Error ...if (scanf( "%lf", &d ) != 1) // Error ...
Note that for ints and doubles, use &i instead of just i (likewise,&d instead of just d). When reading strings with scanf, you don’tneed the &.
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Reading a whole line with fgets.
You can use scanf to read a whitespace delimited string. If youwant to read a whole line (i.e., a newline delimited string) usefgets.
char string[100];FILE *f;f = fopen("data.txt", "r" );if (!f) { perror("Error"); exit(10); }
while( fgets( string, 100, f ) != NULL ) {/* process line */....
}fclose( f );
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
The Gory Details.
C assumes that the programmer means what he/she says.
in other words
C makes it easy for the programmer to shoot him/herselfin the foot.
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Introduction
C-strings can be thought of as a bounded array of characters.
The compiler and run-time environment don’t do automaticbounds checking or automatic overwrite detection.
The programmer must take care to avoid memory corruption!
C-strings (and more generally, memory management) are afrequent source of bizarre programming errors.
Seemingly unrelated bugs are often caused by improper stringhandling.
Intel CPU’s and Unix use byte addressable memory. (So dopretty much all CPU/OS combinations.)
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
A Simple String.
Note: This isn’t exactly how thingswork in memory, but it works for ourpurposes.
char buf[10] = "Hello!\n";
The variable buf is actually a”pointer” to where, in memory,the string is located.
In C, a string ends with a NULL(’\0’) character. Some stringoperations, like the stringdeclaration above, willautomatically append the NULLterminator. Sometimes though,we have to NULL-terminate astring ourselves.
0x1000
Variable Name
0x1004buf
Hello!\n\0
0x5000
0x5000
Memory Address Memory Contents
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Copying a string.
You must use a function like strncpy to copy a string. Theassignment operator will do a ”pointer copy”, it won’t copy thecontents of the string.
char *buf1 = "Hello";char buf2[100];
buf2 = buf1; /* incorrect */strncpy( buf2, buf1, 100 ); /* correct */
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Multiple Strings that use the same memory.
Consider the following code:
char buf[20] = "Hello, World!\n";char *buf2 = buf + 7;
printf("buf: %s\n", buf);printf("buf2: %s\n", buf2);
buf2[0] = ’M’;printf("buf: %s\n", buf);
What is the output?
Variable Name
5000
Memory Address Memory Contents
buf210001004
5000500150025003
500650075008
501050115012501350145015501650175018
5009
50055004
H
o,
el
’ ’World!\n\0
l
buf5007
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
’char *’ versus ’char string[100]’.
(1) char *no_space_buffer;(2) char buffer_with_space[100];(3) char *class_name = "C201: Advanced Programming ...";
Often you will see strings declared in one of these ways. Thedifference is that ’char buffer with space[100]’ explicitlytells the compiler to allocate 100 bytes of storage. With the ’char*’ declaration, storage must come from somewhere else.Declaration (3) will cause the compiler to allocate space for thisstring on the string table.
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Access a single character in a string.
Use the [] operator to access a single character in a string.
char *str = "Hello";printf( "The second character of %s is %c.\n",
str, str[1] );
Notes:
Use %c to print a single character with printf.
Note that in C, like in Java, arrays start at 0, not 1.
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Character literals.
Character literal are enclosed in single quotes (i.e., ’, not ”).
char buf[10];
buf[0] = ’A’; /* correct */buf[0] = "A"; /* incorrect */buf[1] = 0; /* NULL terminator */
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Multiple strings and Buffer overflow.
Strings in C don’t ”grow” automatically. In-stead, the programmer must always be awareof how much space is available. Consider thisexample.
char s1[10]; char s2[10];
strcpy( s1,
"This string is to long!\n" );
We are copying 25 bytes into a 10 byte buffer!The compiler and run-time environment will notdetect this! We have overwritten string s2!Since the string is 25 characters and s1 and s2
are 20 characters total, we have written off theend of our own memory and have potentiallycorrupted the program’s call stack!
Variable Name
5000
Memory Address Memory Contents
s1s2
10001004
5000500150025003
500650075008
501050115012501350145015501650175018
5009
50055004
5010
’ ’
g’ ’
s
This
strin
i
’ ’
ot
’ ’l
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
strncpy
To make string handling safer, the C string library provides afunction called strncpy.
char global_name[100];...voidsave_name( const char *n ){
strncpy( global_name, n, 100 );global_name[99] = 0;
}
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
More about strncpy
If you carefully read the strncpy man-page, there are two(not-so-obvious) things to keep in mind.
1 If there is not enough space in the buffer, strncpy may notNULL terminate the string.
2 If you write 8 bytes to a 10 byte buffer, the remaining 2 bytesare set to the NULL character. The caveat is that if you havea 10 bytes buffer and you do a
strncpy( buffer, stuff, 20 );
you will overflow 10 bytes off the end of buffer even ifstuff will fit in buffer.
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
The string library
Some useful string handling functions in the C string library.
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
strcpy, strncpy: Copy in-memory string data.
strcmp, strncmp: String comparison. Returns zero if stringsare identical.
strlen: Get the length of a string.
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
More on strncmp.
strncmp is also useful for testing the prefix of a string.
char *string = "Hello, World!";
if( strncmp( string, "Hello", 5 ) == 0 ) {printf("This string begins with Hello.\n");
}
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
String parsing with scanf.
Say you have some data in a string buffer that was read withfgets. And you want to grab the data out of it.
char *str = "100 feet 3.14159 Pi";int i; double pi;
sscanf( str, "%d feet %lf", &i, &pi );
Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
Another function that is useful for string parsing is strchr. Thisfunction will search for a character in a string. strchr will returna pointer to the character. If the character cannot be found, NULLis returned.
char *buf = "Hello, World!\n";char *pc;
pc = strchr( buf, ’ ’ );if( pc == NULL ) {
/* space not found. */}else {
printf("pc: %s\n", pc );}
What is the output?Mike Closson C-Style Strings
Introduction to printf and scanfA conceptual model of a C-string
String handling functions in the C standard libraryString parsing functions
Stuff to learn on your own
More string library functions:
String concatenation: strcat, strncat
Finding a character in a string: strrchr, index, rindex
Find a substring: strstr
More string parsing functions: strsep, strspn, strtok
For more information: man string
Mike Closson C-Style Strings