\documentclass[10pt,hyperref={implicit=true}]{beamer}

\mode<presentation>
{
  %\usetheme{Warsaw}
  \usetheme[hideothersubsections]{Goettingen}
  % or ...

  \setbeamercovered{transparent}
  % or whatever (possibly just delete it)

  \subject{C Programming for Engineers}
}
\mode<article>
{
  \renewcommand{\floatpagefraction}{0.75} % default is .5, to increase
  % density.
  \renewcommand*{\bottomfraction}{0.6} % default is 0.3
  \renewcommand*{\topfraction}{0.85} % default is 0.7
  \renewcommand*{\textfraction}{0.1} % default is 0.2
}


\usepackage[english]{babel}
\usepackage{alltt,booktabs,array,cols,multicol,meta}

\usepackage[utf8]{inputenc}
% or whatever
\usepackage{lgrindsetup}

\usepackage{times}
\usepackage[T1]{fontenc}


% See section 5.1, page 44 of the xcolors manual:
% black blue brown cyan darkgray gray green lightgray magenta violet
% orange white purple yellow red

\newcommand*{\red}[1]{\textcolor{red}{#1}}
\newcommand*{\blue}[1]{\textcolor{blue}{#1}}
\newcommand*{\brown}[1]{\textcolor{brown}{#1}}
\newcommand*{\cyan}[1]{\textcolor{cyan}{#1}}
\newcommand*{\darkgray}[1]{\textcolor{darkgray}{#1}}
\newcommand*{\gray}[1]{\textcolor{gray}{#1}}
\newcommand*{\green}[1]{\textcolor{green}{#1}}
\newcommand*{\lightgray}[1]{\textcolor{lightgray}{#1}}
\newcommand*{\magenta}[1]{\textcolor{magenta}{#1}}
\newcommand*{\violet}[1]{\textcolor{violet}{#1}}
\newcommand*{\orange}[1]{\textcolor{orange}{#1}}
\newcommand*{\white}[1]{\textcolor{white}{#1}}
\newcommand*{\purple}[1]{\textcolor{purple}{#1}}
\newcommand*{\yellow}[1]{\textcolor{yellow}{#1}}
\newcommand*{\emphcolour}[1]{\emph{\textcolor{red}{#1}}}
\newcommand*{\ered}[1]{\emph{\textcolor{red}{#1}}}
\newcommand*{\eblue}[1]{\emph{\textcolor{blue}{#1}}}
\newcommand*{\ebrown}[1]{\emph{\textcolor{brown}{#1}}}
\newcommand*{\ecyan}[1]{\emph{\textcolor{cyan}{#1}}}
\newcommand*{\edarkgray}[1]{\emph{\textcolor{darkgray}{#1}}}
\newcommand*{\egray}[1]{\emph{\textcolor{gray}{#1}}}
\newcommand*{\egreen}[1]{\emph{\textcolor{green}{#1}}}
\newcommand*{\elightgray}[1]{\emph{\textcolor{lightgray}{#1}}}
\newcommand*{\emagenta}[1]{\emph{\textcolor{magenta}{#1}}}
\newcommand*{\eviolet}[1]{\emph{\textcolor{violet}{#1}}}
\newcommand*{\eorange}[1]{\emph{\textcolor{orange}{#1}}}
\newcommand*{\ewhite}[1]{\emph{\textcolor{white}{#1}}}
\newcommand*{\epurple}[1]{\emph{\textcolor{purple}{#1}}}
\newcommand*{\eyellow}[1]{\emph{\textcolor{yellow}{#1}}}
\renewcommand*{\alert}[1]{\emph{\textcolor{red}{#1}}}

% Or whatever. Note that the encoding and the font should match. If T1
% does not look nice, try deleting the line with the fontenc.

\title{Writing Portable and Safe C/C++ Programs}
\subtitle{C Programming for Engineers}

\author[Nick Urbanik]{Nick Urbanik \texttt{\footnotesize{}nicku\at{}nicku.org}\\
  {\tiny This document Licensed under GPL---see slide~\pageref{sld:license}}%
}

\date{2005 September}

% Copyright (C) 2005  Nick Urbanik <nicku@nicku.org>

% You can redistribute modified or unmodified copies of this document
% provided that this copyright notice and this permission notice are
% preserved on all copies under the terms of the GNU General Public
% License as published by the Free Software Foundation--either version 2
% of the License or (at your option) any later version.

\AtBeginSubsection[]
{
  \begin{frame}<beamer>
    \frametitle{Outline}
    \footnotesize
    \begin{multicols}{2}
      \tableofcontents[currentsection,currentsubsection]
    \end{multicols}
  \end{frame}
}

% If you wish to uncover everything in a step-wise fashion, uncomment
% the following command: 

%\beamerdefaultoverlayspecification{<+->}

\newcounter{program}
%\newcommand*{\program}[1]{\refstepcounter{program}\label{#1}\arabic{program}}
% \newcommand*{\program}[1]{%
%    \refstepcounter{program}\hypertarget{#1}{Program \texttt{#1}}%
% }
%\newcommand*{\program}[1]{\refstepcounter{program}\label{#1}\arabic{program}}
\newcommand*{\program}[1]{%
   \hypertarget{#1}{Program \texttt{#1}}%
}

\newcommand*{\linkto}[1]{\hyperlink{#1}{\texttt{#1}}}
\providecommand*{\bs}{\texttt{\char '134}} % Backslash, no break

\begin{document}
\maketitle
\thispagestyle{empty}

% \begin{frame}
%   \titlepage
% \end{frame}

\begin{frame}
  \frametitle{Outline}
  \mode<presentation>
  {%
    \footnotesize
    \begin{multicols}{2}
      \tableofcontents
    \end{multicols}
    % You might wish to add the option [pausesections]
  }%
  \mode<article>
  {%
    \tableofcontents
  }%
\end{frame}

\section{Portable Programming}

\subsection{What is a ``portable'' program?}

\begin{frame}
  \frametitle{What is a ``portable'' program?}
  \begin{itemize}
  \item A \alert{\emph{portable program}} can be compiled and will run
    successfully on many different \alert{compilers}, \alert{operating
      systems} and \alert{hardware platforms} with \alert{little or no
      change} to the source code
  \item \ered{Changes} will be \ered{easier to make} to enable this
    program to run on a \eorange{new platform}
    \begin{itemize}
    \item compared with a program that was not written with care about
      portability.
    \end{itemize}
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Way to reduce portability problems}
  \begin{itemize}
  \item Avoid \ebrown{proprietary} or \alert{non-standard libraries}
  \item Avoid assumptions about the \alert{size of data}
    \begin{itemize}
    \item Use the definitions in \red{\texttt{limits.h}} and
      \red{\texttt{math.h}}
    \end{itemize}
  \item Avoid assumptions about the \alert{\emph{order}} and
    \alert{arrangement of data}
    \begin{itemize}
    \item Some machines are \epurple{big-endian}, others (such as the PC) are
      \epurple{little endian}
    \end{itemize}
  \item Put \alert{architecture-dependent code} into a \alert{separate module}
  \item Be careful when you specify \alert{file names}
  \item Use the ``\purple{\texttt{binary}}'' type when you
    \epurple{read/write} \alert{binary files}, even if it is not
    required on your platform
    \begin{itemize}
    \item otherwise the compiler will treat your file as a text file
      and corrupt it
    \end{itemize}
  \end{itemize}
\end{frame}

\subsection{Standard Library Functions}

\begin{frame}
  \frametitle{Standard Library Functions}
  \begin{itemize}
  \item I see lots of you using the \texttt{conio.h} header.
  \item Please use this \emph{only} when absolutely necessary!
  \item Use standard library functions wherever you possibly can.
  \item \ered{Avoid} using \purple{library functions that start with
      an underscore}, such as \purple{@_rotr()@} provided by the
    Borland 3.1 compiler, and declared in the \texttt{stdlib.h}
    ``standard'' header file!  \red{\texttt{:-)}}
  \end{itemize}
\end{frame}

\subsection{Size of Data}

\begin{frame}[fragile]
  \frametitle{Size of Data}
  \begin{itemize}
  \item Many homework exercises \purple{assumed that integers are 16
      bits long}\ldots
  \item \ldots\,this code will \eblue{not} run correctly under a 32-bit
    operating system such as Windows XP or Linux!
  \item Use \red{@sizeof@} and the constant \violet{@CHAR_BITS@}
    defined in {}%
    @#include <limits.h>@\ %
    if you need bit-level information about the size of
    data on your platform.
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Size of Data: Examples}
  \begin{itemize}
  \item Code with \alert{many} assumptions about data size:
%[
void bin1( unsigned int d )
{
    for ( int i = 0; i < 16; i++ ) {
        int a = ( ( d & 32768 ) == 0 ) ? 0 : 1;
        cout << a;
        d <<= 1;
    }
}
%]
  \item Code with fewer assumptions about data size:
%[
#include <limits.h>

const int numbits = CHAR_BIT * sizeof( int );

void printbinary( int n )
{
        for ( int i = numbits - 1; i >= 0; --i ) {
                cout << ( ( 1 << i ) & n ? "1" : "0" );
        }
}
%]
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Exercise: \red{two minutes}}
  \begin{itemize}
  \item Form a \green{two-person group} with the person next to you
  \item Discuss ways you could make \egreen{your own code that you
      have given for homework} \ered{more portable}.
  \item Be ready to \eorange{report back} to the class the ways your
    group could improve the portability of your code.
  \end{itemize}
\end{frame}


\subsection{Order and Arrangement of Data}

\begin{frame}
  \frametitle{Order and Arrangement of Data}
  \begin{itemize}
  \item Suppose on some computer
    \begin{itemize}
    \item a long is 32 bits in size
    \item the address of the long variable is 0xb0123456
    \item we put the long value 0x12345678 in this variable.
    \end{itemize}
  \item What byte is stored at 0x12345678?
    \begin{itemize}
    \item is it 0x12 or 0x78?
    \end{itemize}
  \item Answer: ``\ered{it depends}''
  \item On a \eblue{big-endian} machine, such as a Motorola Dragonball
    processor, the answer is 0x78
  \item On a \eblue{little-endian} machine, such as a PC, the answer
    is 0x12
  \item Do not write code that assumes either.
  %\item Also'' do not assume that fields of a structure follow each
  %  after the other
  \end{itemize}
\end{frame}

\section{Safe Programming}


\subsection{What is a secure program?}

\begin{frame}
  \frametitle{What is a ``safe'' program?}
  \begin{itemize}
  \item A secure program cannot be easily exploited by a malicious
    person to gain privileges that they should not have
  \item A secure program will run more \ered{reliably}
    \begin{itemize}
    \item Not ``sometimes run okay, other times it \blue{crashes}''
    \end{itemize}
  \item Symptoms of possible security problems include:
    \begin{itemize}
    \item occasionally \ered{terminates} with a ``\egreen{segmentation
        fault}'' or ``\eblue{protection error}''
    \item data occasionally appears with unrecognisable garbage
      appended
    \item changing one data item causes another unrelated data item to
      change
    \end{itemize}
  \end{itemize}
\end{frame}

\subsection{Main sources of problems}


\begin{frame}
  \frametitle{Main sources of problems}
  \begin{itemize}
  \item Writing \ered{past the end of arrays} on the stack
    \begin{itemize}
    \item Exploited by crackers as a technique described in
      \emph{Smashing The Stack For Fun And Profit} by Elias Levy (aka
      Aleph One) at \url{http://www.insecure.org/stf/smashstack.txt}
      and \url{http://www.phrack.org/show.php?p=49&a=14}
    \end{itemize}
  \item writing to \ered{uninitialised pointers}
  \item \ered{memory allocation} errors:
    \begin{itemize}
    \item allocating memory without freeing it (``memory leak'')
    \item freeing memory twice (``double free'')
    \end{itemize}
  \end{itemize}
\end{frame}

\subsection{Avoiding Buffer Overflows}

\begin{frame}[fragile]
  \frametitle{Avoiding Buffer Overflows}
  \begin{itemize}
  \item When reading strings into arrays, always use techniques that
    limit the data read into  the string and make sure it is null
    terminated.
  \item With iostreams:
    \begin{itemize}
    \item use the @istream::getline()@ method to read input lines,
      limiting the number of bytes read to the length of the buffer
    \item \eblue{or} you can use the @setw()@ iostream manipulator to
      limit characters read (@#include <iomanip>@)
    \end{itemize}
  \item \ered{\LARGE{}Never} use the @gets()@ library function
  \item use @stncpy()@ rather than @strcpy()@, use @strncat()@ rather
    than @strcat()@, \ldots
  \item Simply make sure that there is \ered{no possibility} of
    writing past the end of an array.
  \end{itemize}
\end{frame}

% \begin{frame}
%   \frametitle{}
%   \begin{itemize}
%   \item 
%   \end{itemize}
% \end{frame}

\subsection{Avoiding writing to uninitialised pointers}

\begin{frame}
  \frametitle{Avoiding writing to uninitialised pointers}
  \begin{itemize}
  \item Before you use a pointer, it has some uninitialised value, and
    points to some \epurple{random location}
  \item You must have the pointer \egreen{point} somewhere --- to
    memory that you own --- \ered{before} you write to the location.
  \item How?  Either:
    \begin{itemize}
    \item make the pointer point to an \eblue{existing variable}, or
    \item \eblue{allocate some memory} dynamically (with the C++ @new@
      operator or the @malloc()@ library function)
    \end{itemize}
  \end{itemize}
\end{frame}

% \begin{frame}
%   \frametitle{}
%   \begin{itemize}
%   \item 
%   \end{itemize}
% \end{frame}

\subsection{Avoiding memory allocation problems}

\begin{frame}
  \frametitle{Avoiding memory allocation problems}
  \framesubtitle{memory leaks and double free errors}
  \begin{itemize}
  \item It is up to you to remember where you allocated memory
  \item For each piece of memory you allocate, it will not be freed up
    till either you free it up, or the program terminates.
  \item If the program will run a long time, and will make many
    allocations, then you need to be like an accountant: you have to
    free it up.
  \end{itemize}
\end{frame}

\section{References}

\begin{frame}
  \frametitle{References}
  \begin{thebibliography}{99}
  \beamertemplatebookbibitems
  \bibitem{Aleph1996}
    Elias Levy, aka Aleph One.
    \newblock%
    \emph{Smashing The Stack For Fun And Profit}.
    \newblock%
    Phrack No. 49, 8 November 1996.
    \url{http://www.phrack.org/show.php?p=49&a=14}.
    \newblock%
    \url{http://destroy.net/machines/security/}.
%   \bibitem{Dean2001}
%     Jeffrey Dean.
%     \newblock {\em LPI Linux Certification in a Nutshell---A Desktop
%       Quick Reference}.
%     \newblock O'Reilly, 2001.

    \bibitem{Oual1993}
      Steve Oualline.
      \newblock%
      \emph{Practical C Programming}.
      \newblock%
      O'Reilly, 1993.
      
      \bibitem{Dav1995}
        Paul Davies.
        \newblock%
        \emph{The Indispensable Guide to C with Engineering Applications}
        \newblock%
        Addison-Wesley, 1995.

        \bibitem{Ker1988}
          Brian W. Kernighan and Desnnis M. Ritchie.
        \newblock%
        \emph{The C Programming Language}.
        \newblock%
        Prentice Hall, 1988.
  \end{thebibliography}
\end{frame}

\begin{frame}
  \frametitle{License covering this document}
  \label{sld:license}
  Copyright \copyright{} 2005  Nick Urbanik <nicku\at{}nicku.org>

  You can redistribute modified or unmodified copies of this document
  provided that this copyright notice and this permission notice are
  preserved on all copies under the terms of the GNU General Public
  License as published by the Free Software Foundation --- either
  version 2 of the License or (at your option) any later version.
\end{frame}

\end{document}
