Summary
Strings
- array of chars that ends with a ‘\0’(null) char
c
// valid strings
char *a = "hello"; // " is used to wrap strings, ' for chars
char b[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
char c[6] = { 'h', 'e', 'l', 'l', 'o' }; // last char is initialized as 0 -> '\0'
// invalid strings
char d[5] = { 'h', 'e', 'l', 'l', 'o' };
Assignment
- same as arrays
- cannot assign after declaration
String functions
string.h
c
strlen(s); // counts upto but not including '\0'
strcmp(s1, s2); // 0 if equal, -ve if s1 < s2, +ve if s1 > s2
strncmp(s1, s2, n); // compare only the first n characters
strcpy(s1, s2); // copy the string at s2 into s1
strncpy(s1, s2, n); // copy only the first n characters
Concept
I/O functions
- reading from
stdin
c
char *str;
scanf("%s", str); // reads until whitespace
fgets(str, size, stdin); // reads size-1 chars or until newline
- printing to
stdout
c
printf("%s\n", str);
puts(str); // terminates implicitly with a newline
will trace through the string until the
'\0'
Application
String terminator
c
char d[5] = { 'h', 'e', 'l', 'l', 'o' };
puts(d); // hello??????... we don't know whats stored in memory after the array
this can leak information about what’s stored in memory
Overflow
c
// strcpy and most fns that don't take into account string length are unsafe
char name[10];
strcpy(name, "Bob Ross"); // 1
strcpy(name, "Ovuvuevuevue Enyetuenwuevue Ugbemugbem Osas"); // 2
a stack canary will protect overflowing in most cases, compile with
-fno-stack-protector
to compile without a stack canary
Removing the newline char
c
fgets(str, size, stdin);
len = strlen(str);
if (str[len – 1] == '\n')
str[len – 1] = '\0';
Jank
c
long x = 470020878965; // 0x00 00 00 6D 6F 6D 72 75
puts((void *)&x); // urmom