COMP 1917 Computing 1
Session 2, 2016

Tutorial - Week 6

String Functions


Presentation Topic for This Week

Explore memory. Find out the number of bytes that C uses on your system to store the various types described below. Hint: You can use sizeof() function to print the number of bytes that given type uses(e.g printf("%lu\n", sizeof(int))
char, int, unsigned int, long long, unsigned long long, float, double
Are types signed or unsigned by default? What are the maximum and minimum values you can store in each of the types? What happens if you add 1 to the maximum value of a type, what happens if you subtract 1 from the minimum value of the type?


  1. Write a function int len_str(char *str) that calculates the length of a string.

  2. Suppose a program myprog has the following prototype for the main function
        int main(int argc, char *argv[])
    
    What are the values of argc and argv[] when the program is invoked from the command line by
        ./myprog -a -bc junk
    
  3. Recall that a string is an array of characters, with the special character '\0' used to mark the end of the string.

    Write a function void reverse_string(char s[]) which reverses a string "in place". For example, the string "live on" would be converted to "no evil". Try to do it by just permuting the elements in the string itself (i.e. without declaring another array inside the function).

  4. Write a function void substr(char s[], char d[], int lo, int hi) where given a string s[], we want to extract from s[] a substring starting at lo and ending at hi inclusive. The resultant substring is to be returned in the character array d[]. Checks must be made to ensure that lo is within the length of s[]; if not, then d[] is an empty string. If s[] is shorter than specified by hi, then d[] contains the substring of s[] starting at lo to the '\0' character.

  5. Write your own version of the library function strstr(), which the on-line manual defines as follows:

         char *strstr( char s[], char d[] )
    
    The strstr() function finds the first occurrence of the substring d in the string s. If d is an empty string, s is returned; if d occurs nowhere in s, NULL is returned; otherwise a pointer to the first character of the first occurrence of d is returned.
    Note: Later in your studies, you might learn more sophisticated ways of implementing the strstr() function which are faster, such as the Boyer-Moore algorithm and the Knuth-Morris-Pratt algorithm (but these are beyond the scope of this course).

  6. If time allows review any questions from previous weeks.

Presentation Topic for Week 7

Explain what is meant by a "Buffer-Overflow Attack". What kind of code is susceptible to such an attack? How can you re-write your code to protect it from this threat?