Tuesday, March 11, 2008

CSE 2031 Lecture 15

Man ulimit | col 0b > foo.mantxt


 

Filesystem

  • Filesystem is an organized structure consisting of many files and / or directories
  • A file is a stream of bytes
    • Stores data
    • Has a name
    • Usually on disk or some other storage medium
  • A directory is a special file in the filesystem which contains files and other directories
  • Unix filesystem
    • Bin
    • Usr
    • Etc
    • Users
      • Admin
        • John
        • steve
      • Staff
      • student
    • lib
  • drwx------
    • read write execute
    • d = filetype
      • d for directory
    • a normal file would have a – where the d is
  • %ln marks cpOfMarks
    • Creates a new link to marks
    • Puts in a new name associated with the same inode number
  • Inode
  • Name
  • 1042
  • Temp
  • 3784
  • Prog.c
  • 4798
  • Marks
  • 4798
  • cpOfMarks
  • you need links if you have a file on another partition
  • pwd shows the current working directory
  • cd changes current directory
  • a path name is a reference to something in the filesystem
  • a path name specifies the set of directories you have to pass through to find a file
  • directory names are separated by "/" in Unix
  • special elements : "." And ".."
  • "." Means "the current directory"
  • ".." means "the parent directory"
  • /dec/tty – the terminal you are using
  • /dev / zero – an input stream which returns an edless stream of null bytes
  • ls day?
    • Ls –ld day?
      • Ls –ld day1 day2 day3 day4 day5
    • The ? goes thru all the files that say day
    • And then wildcards the rest of the names

Thursday, March 6, 2008

2031 Lecture 14

Check your assignment 1 q2.c for 'ERANGE' without this it is wrong apparently

  • Fork
  • Exec
  • Open
  • Close
  • Dup/dup2
  • Lseek
  • Read
  • Write
  • Pipe
    • Sets up a pip
      • Writes to this end à |===========| ßreads from this end
      • pipe( an array )
        • int fd[2]
        • pipe(fd)
        • fd[0] reads from the pipe
        • fd[1] writes to the pipe


 

#include <>

#include <>

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>


 

int main(void)

{

    int fd[2];

    pipe(fd); /* should check return value but in this example we are not*/


 

    switch(fork())


 

case -1:

    perror ("Bad fork()");

    exit(1);

case 0:

    execlp("who", "who", NULL); // first who is the command second is the argument vector

    fprintf(stderr, "should not get this far: bad exec");

    exit(1);

default:

    switch(fork())

    {

    case -1:

        perror ("Bad fork()");

        exit(1);

    case 0:

        close(fd[0]);

        dup2(fd[1], 1); /*file descriptor you want to duplicate, and file descriptor you want to duplicate it to*/

        close(fd[1]); // fd will now write into the pipe


 

    default:

        wait((int *)0);

    wait((int *)0);

    exit(0);

    }

}

/*wthin a program we want to write a program we are going to open a file called temp and we will write printf statements and they will go into temp instead of a stream, there are

two ways to do this, one way is you can open a file called temp

write(fd, ....);

or

dup2(fd, 1) fd , 1 == standard output

any statement after this will print to fd instead of stdio

after this we can say close(fd); and this will still write to that file.. you do not get stdio back.


 


 

-----------------------

assignment q2.c

------------------------

illegal input if it doesn't take 2 ints or line is too long


 

#include <stdio.h>

#include <string.h>

#include <limits.h>

#include <errno.h>

#include <stdlib.h>


 

void finishLine(FILE * fp, char * buf, size_t bufSize);


 

int main(void)

{

/*

a buffer to hold line read in.

add 2 for '\n; the '\0' added by fgets

*/

char buf[MAX_LENGTH + 2];

long
int n1, n2;

char * p;

char x[1];


 

/*

printf("%1d\n", LONG_MAX):

printf("%1d\n", LONG_MIN):

/*

/* main loop reads a line at a time */

while ((p=fgets(buf, sizeof(buf), stdin)) != NULL)

{

    /* errno may have been set on previous iteration.*/

    errno = 0;

    /*

check whether whole line read in.

if not line was too long.

     */

    if (strchr(p, '\n' == NULL %% strlen(p) > 50)

            /*line too long.*/

            {

        /*output message */


 

        printf("illegal input\n");


 

        /* read and ignore rest of line*/

        finishLine(stdin, buf, sizeof(buf));


 

        /* get next line if one exists*/

        continue;

            }

    /* if we reach here, line is not too long */

    /* read from the line now stored in the buffer.

reading into dumm x detects extra tokens on 1


 

we expect exactly 2 interger tokens.

note: in sscanf, the ...%1x... is one x, not..

/*

if (sscanf(buf, "%1d %1d %1s" , &n1, &n2, x) != 2) /* the scan f returns the number of conversions*/

    {

        printf("illegal input \n");

        continue;

    }

    /* if we readch here, input consists of exactly 2 integers*/

    /*

check fo roverflow or underflow in n1 and n2. note that we'll have to read n1 and n2 again

     */

    n1 = strtol(buf, &p, 10);


 

    if (n1 == LONG_MAX && errno == ERANGE)

    {

        print("overflow\n";

        continue;

    }

    if (n1 == LONG_MIN && errno == ERANGE)

    {

        printf("underflow\n");

        continue;

        n2 = sscanf(p, "%1d", &n2);

        n2 = strtol(p, &p, 10);

        if (n2 == LONG_MAX && errno == ERANGE)

        {

            printf("overflow\n");

            continue;

        }

        if (n2 == LONG_MIN %% errno == ERANGE)

        {

            printf("underflow\n");

            continue;

        }

        /* if we reach here both ints are legal and there is no other input other than 2 ints which is what we want*/

        /* strtol stops when it gets to something that isn't a digit, if what it reads is larger than long max it will return long max and set errno*/


 

Tuesday, March 4, 2008

CSE 2031 Lecture 13

fork()

getpid() // get process ID

getppid() // get parent process ID


 

fork is a system call w/ no arguments but it returns a value

the parent and the child see different return values

the newly created child see's return value 0

the parent that called fork see's a nonzero return value, namely the ppid of the newly created child


 

a child finds a parents process ID by calling getppid()


 

when a child terminates, OS saves PID, exit status, cpu time ... of child

and passes this to the parent when parent calls wait() or waitpid


 

until then the child is a 'zombie'

the OS can't free up the resources for the child until the parent waits on the child

if the parent finishes before the child, then the child is reparented

    wait

            - block until first child finishes

    waitpid

        - block

        -specify which child to wait for

pid of child <- wait(int*)

int status

wait(&status)


 

%a.out

    - what we have here is the shell foks off a child and waits for the child to return

    child - executes a.out

    once done the parent outputs the prompt and waits for another command to be inputted

if %a.out &

    -the shell doesn't wait.

-----------------------------------------------------------------------------------------------------------------------------------------------


 

#include <stdio.h>

#include <sys/wait.h>

#include <sys/types.h>

#include <unistd.h>

#include <stlib.h>


 

#define MAX 10

int main(void)

{


 

int i;

fork();

fork();

printf("Hello\n");

return 0;

}


 

// prints 4 'Hello" lines

-----------------------------------------------------------------------------------------------------------------------------------------------


 

#include <stdio.h>

#include <sys/wait.h>

#include <sys/types.h>

#include <unistd.h>

#include <stlib.h>


 

#define MAX 10

int main(void)

{


 

int i;


 

switch(fork())

{

case -1:

    perror("Bad fork");

    exit(1)

case 0:

    /* CHILD */

    for (i=0; i < MAX; i++)

    {

        printf("CHILD\n");

    }break;

default:

    /* PARENT */

    for(i = 0; i < MAX; i++)

    {

        printf("\tPARENT\n");

    }

    printf("pid = %d\n", getpid());

    printf("ppid = %d\n", getppid());

return 0;    


 

}


 

/*prints CHILD 10 times, pid = 2153, ppid = 2152, prints PARENT 10 times then , pid = 2255, ppid = 27289

eventually the parent executes before the child because it is left to the OS to decide the PPID*/

/* if wait((int * ) 0);

was typed after /*PARENT*/ it will always print CHILD first*/


 

along with fork() there is exec()


 

%a.out hello there world becomes


 

argv -> -> a.out

->hello

->there

->world

->null


 

-------------------------------------------------

execlp("cat", "-n", "temp", NULL);

"cat"

Thursday, February 21, 2008

CSE2031 lecture 12

SystemCalls

  • Check out these books
    • Stevens Advanced Programming in the unix Environment
    • Robins&Robins – unix systems programming

  • Processes
    • Fork
    • Exec….


     

  • Files
    • Open
    • Close
    • Read
    • Write
    • Lseek
    • Dup
    • Dup2


 

PerProcess file Descriptor table

System wide open file table

I-Nodes

File descriptors

Flags

Disk / device

0

Offset

 

1

To i-node

 

2

  

..

  
  • Write(fd,buf,50)
    • Fd
      • File descriptor
    • Buf
      • Void* char
    • 50
      • #bytes
  • Write(fd,"Hello",6)
    • If this was typed after the first line there would be an offset of 56
  • Lseek
    • Lseek(fd,offset,WHENCE)
      • Fd
        • File descriptor
      • Offset
      • WHENCE
        • SEEK_SET
        • SEEK_CUR
        • SEEK_END
  • Dup
    • Duplicates a file descriptor using another file descriptor
      • Int dup(int oldfd);
      • Int dup2(int oldfd, int newfd)
    • Why would you want to do that?
      • Because you would never want to do this
        • Dup2(fd,1);
          • First argument is one you want copied
          • Second is what you want it copied on
        • Close(fd);
        • Printf("hello\n";
        • This would write at a file temp

int a[15]


 


 

int (*a)[15] /** a is a pointer to an array of 15 ints**/


 

int fd

fd = open("temp", _|_|_, 0660)

/*for the last input '0660' there should always be a leading 0 because it is an octal*/

/*_| represents space for flags*/


 

#define    O_WRONLY    1<<4

    O_TRUNK    1<<2

---------------------------------------

fd = open("temp", ..flag..)

write(fd,...)

close(fd)x

---------------------------------------


 

always check the return value from a system acall


 

if((fd = open("temp", ..flags..))<0){perror("...."); exit(1)}


 

for every file there exists an 'I-Node"

along with an I-Node there is a system-wide openfiletable

and with that there is a perprocess file descriptor table

Tuesday, February 19, 2008

CSE2031 Lecture 11

    #include<stdio.h>


 

int main(int argc, char* argv[])

{


 

return 0;

]


 

-------------------------------------------------------------

command line arguments

-------------------------------------------------------------

args can be accessed just like a normal allocated array

printf("%s\n", argx[2]);


 

-------------------------------------------------------------

bit operations

-------------------------------------------------------------


 

used to be used to pack and unpack things into small space, but space is cheap now.


 

operating on bits


 

logical operators (unary) bitwise complement ~

    bitwise AND    &

    bitwise XOR    `

    bitwise OR    |


 

shift operators

    left shift        <<

    right shift        >>


 

do not confuse & with &&

     or | with ||


 

right shift shifts in ?? on left end

for unsigned, zeros shifted on the left end

for signed, machine dependent

    -shift in zeros

    -shit in sign bits

int    a=1 << 31; /* shift 1 to high bit*/

unsinged    b = 1 << 31;


 

expn        representation

a        10000000 00000000 00000000 00000000

a >> 3        11110000 00000000 00000000 00000000

b        10000000 00000000 00000000 00000000

b >> 3        00010000 00000000 00000000 00000000


 

to turn bits on , use OR and 1's

v | 3 << 2

v | 00000000 00001100

has 3rd and 4th bit on, others as in v


 

to turn bits off, use AND and 0's

    v & ~(3<<2)

    v & 11111111 11110011

    has 3rd and 4th bit off, others as in v


 

masks


 

    -a string of bits used to extract bits from another expression

    -to find value of a particular bit in an expression

    - use a mask that is 1 at that bit and 0


 

otherwise


 

    1 << 2 as mask to query 3rd bit in v

    (v & (1 << 2) ) ? 1 : 0


 

    has value 1 if 3rd bit in v is 1 and 0 otherwise


 

bit representation of 255

    00000000 00000000 00000000 11111111

    

    0    --> all 0's

    ~0     --> all 1's

    ~0<<k     --> 111...11 000..0

~0(~0<<k)<<r     --> 000..0 11111111 000.00


 

Thursday, February 7, 2008

CSE2031 Lecture 10

Specifier

Field type

Converted using

Arg is pointer to

d

Integer (optionally signed)

Strtol with base 10

Int

hd

''

''

Short int

ld

''

''

Long int

I

''

Strtol with base = 0

Reads 045 as octal

Ox92 as hexadecimal

 

hi

  

Short

li

''

''

Long

O

Integer

Strtoul base 8

Unsigned int

ho

''

''

Unsigned short

Lo

''

''

Unsigned long

U

''

Base 10

''

Hu

''

''

''

Lu

''

''

''

X

Integer

Strtoul base 16

Does not accept AB

Unsigned int

Hx

''

''

''

Lx

''

''

''

E

Floating point input field

Strtol

Float

le

''

''

Double

Le

''

''

Long double

    


 


 

fscanf

-----------------------------------------

#include <stdio.h>

int fscanf(FILE*stream, const char * format, ...)

scanf is like fscanf(stdin,...)

sscanf(const char* src, ...format...

return value = # of text fields converted to values that are stored

scanf("%d %f", &n,&x)

return EOF if the function stops scanning

because the attempt to get next character it sets end of file or error indicator

for stream ferror(fp), feof(fp)

--------------------------------------------

format string

---------------------------------------------

can have white space

matches any amount of whitespace in the input

"%d<>%f

<> represents a space

literal text

scan conversion specifier

    -like those from printf ( sort of )

-------------------------------------------------

conversion specifier

---------------------------------------------------

-start w/ % sign

-*assignment supression

    looks like scanf(%d %*d %d &m)

-w field width

-conversion specifier

    -give type of argument to expect

        -always a pointer to something

    -how to determind conversion field

    -how to convert value to store

    

(a) scan set

[ ]

keep reading any of these characters (above)

{^ }

Don't read these characters (above)

b) otherwise (and usually)

    d

    i

    o    hl

    u

    x

    X

d and i are different in scan f


 

    eE

    fF    lL

    gG


 

    c

    s

    n

    p


 

-------------------------------

%wc    w chars no '\0' appended        store arg char*

defaults to 1 for %c


 

%ws    w chars                charx then append '\0'

default %s all of next token


 

scanf("%10c", buf)             reads first 10 chars even if it is whitespace

scanf("%10s", buf)            skips all the whitespace reads first 10 chars


 

char *p;

strtol(" 347atx ", &p, 6);

//skips whitespace and reads legal digits in 'this' base (this being 6)

//returns 22 (3 sixes + 4) and pointer p points to the 7

if value outside the range it will return LONG_MAX/ LONG_MIN + set errno to ERANGE

0 <-- system call

-1

x

---------------------------

file* <--Fopen

NULL

x

------------------------------

perror("usermessage");            prints out "usermessage: system error messsage" error message corresponding to error number

strerror(errno)                 returns appropriate error string


 


 


 

            

Tuesday, February 5, 2008

CSE 2031 Lecture 9

Assignment FAQ

Output files as they are read. For first question : instead of outputting palendromes output 'line is too long' after a certain length.

file* ß fopen(…)

file* fp;

fp = fopen("temp","a");

fprintf(fp,'%s\n", "Hello");

.

.

.

fclose(fp);

printf == fprintf(stdout,…);

"r+" opens a file for reading and writing

"w+" creates a file or truncates it if it exists and reads and writes to it

File descriptor talks to offset talks to inode

When you give a command like write you specify a file descriptor, where you find the data and how much you want to write

A file is a sequence of bytes,

Fseek, frewind, fsetpos are ways to specify the file pointer and where in the file you would like to go in the offset

States of a stream

  • Opened
    • If you write you go to ..
      • Writing state
        • If you continue writing you stay in the write state
        • If you use seek or rewind you will go back to
          • Opened state
        • If you just finished writing then you read
          • Error state
    • If you read you go to
      • Reading state
        • If you continue reading you stay in the read state
        • I f you just finished reading then you write
          • Error state


 

Printf(format string; other args)

Format string

  • Literal text
  • Conversion specifier
    • Printf("hello world \n");
    • ^literal text
  • Printf("n=%d\n", n);
    • Literal text
      • "n=" + "\n"
    • Conversion specifier
      • "%d"
    • Other arguments
      • "n"
  • Using print f
    • A char and short is always converted to int
    • A float is always converted to double

Conversion specifier

  • Starts with "%"
    • 4 components (in order)
      • Flags
      • Field width
      • Precision
      • Conversion specifier
        • first 3 are optional


 

d,i

Int

[-]ddd (where d are digits)

u

Unsigned int

ddd

o

Unsigned int

ddd 0-7

x

Unsigned int

ddd 0-9 a-f

X

Unsigned int

ddd 0-9 A-F


 

f

Double

[-]ddd.ddd

E,e

Double

[-]d.ddd e/E +/- dd

G,g

Double

-4<= exponent <precision (life f or e,E

c

Int

Treats int as unsigned char

Prints the character

S

Char*

Output chars from array up to '\0'

P

Void*

System dependant

Prints an address, usually in hexidecimal

N

Int*

Stores in variable; # of characters printed so far. No conversion

%

 

Writes a '%' sign


 

Length specifier in conversion specifier

  • h,l,L
  • you can have the h in front on the integer conversion specifiers
    • conversion specifier applies to short int (unsigned short int)
    • remember char / short args already promoted to int
    • convert arg to short before printing
  • the L,f,e,E,g,G conversion specifier applies to long double argument
  • do now use lowercase l or h with f,e,E,g,G

flags

  • field width
    • %5d
      • Decimal no sign
      • Field width of size 5
    • %-d
      • Fiend width 5
      • '-' is a flag
        • Left jusitication
    • %*d
      • Take next arg as field width
      • Scanf("%*lf, …)
        • * in scanf the * says read a double from input

Precision

  • After the period
  • %.5d
    • Min # digits to output, pad left w/ 0's
  • %.5f
    • # of fraction digits
  • %.5g
    • Max # of significant digits
  • &.5s
    • Max # of characters to print from the string

Flags

  • -
    • Left justify
  • 0
    • Pads with 0's
  • +
    • Forces explicit plus sign
  • ' ' (space)
    • Use a space instead of plus sign in the output
  • #
    • Changes conversions
    • 0 à leading 0
    • %#F
      • The decimal sign is printed even if there is nothing after it

EATS 1011 Lecture 10

Clouds

Nacreous clouds

  • A form of PSC (~10 microns)
  • Formed by waves over mountains
  • Text and other locations: nacreous clouds
  • PSC
    • Polar stratospheric clouds
  • Located about 15-25km
  • Winter polar stratosphere is very cold 180-190 K
  • HNO3 and water form ice clouds
  • Ice surfaces catalyse conversion of HCL to CL which attacks ozone and creates ozone hole
  • Contains:
    • H2O, h2SO4, HNO3, HCL

Noctilucent Clouds

  • Only appear in polar regions
  • Size ~.1 microns or smaller
  • Very thin layer clouds:
    • Hard to see over head
    • Only visible at twilight or later w/ a long path for illumination
  • At the summer mesopause
  • Very cold ~100-140 K
    • 173 to 133 degrees celcius
  • Frozen water
  • Ccn probably meteoritic dust
  • Wave structures revealed in ice formation
  • Can be warning of increased methane (CH4)`

Lapse Rates

  • Environmental
  • Γe environmental lapse rate
    • dT/dz = ΔT /ΔZ = - Γe
    • 'dry' adiabatic
      • g/Cp = Γdry
    • 'moist' adiabatic
      • g/Cp = Γmoise
    • ΓMoist < ΓDry
  • Depends on the planet and the major gas
  • AIR PARCEL(AP)
    • Think of an isolated unit of air maintaining its integrity
    • This doesn't work for long because of exchange of molecules etc
  • Lapse rate is how the temp is going to change in height
  • A steep lapse rate means large temperature change
  • Adiabatic
    • No exchange of energy with outside
  • Cooling
    • Important in Cloud formation and rain
  • Mean global rate
    • ~6.5 C/Km
    • Inversion, temperature increases with height
  • Specific heat @ constant pressure Cp energy add to raise temp 1Celsius for 1kg @ constant pressure
  • Specific heat @ constant Volume Cv energy add to raise temp 1Celsius for 1kg @ constant pressure
    • Cp(air) = 1007 J/kg/Kelvin
      • For one Kg you have to have supply 1007 joules for 1 degree celcius difference
    • Cv(air) = 700 J/kg/Kelvin
  • − T2 ) / (Z2 – Z1) = (-g)/Cp
    • Dry adiabatically
  • -(T1MCp)
    • Extract heat
  • + Mg(z2-z1)
    • Add potential energy
  • + CpMT2
    • Add heat

Thursday, January 31, 2008

CSE2031 Lecture 8

  • When creating a struct no space is allocated
  • typedef
    • Make a new type name
  • Typedef double grade
    • "grade" is now a new type
    • grade g1 = 3.5
      • Grade can be used whenever double is used
    • Typedef unsigned int size_t;
    • Typedef void (*_sighandler_t)(int)
  • Pointers to structs
    • Structpoint p1;
    • Structpoint* pp;
    • pp = &p1;
    • the name of a struct is not a pointer to the beginning of the variable
    • p1.x = 9
    • *pp.x = 9 //doesn't work
      • Because dot operator has precedence over *
    • (*pp).x = 9
      • // will properly dereference the struct
    • ppàx = 9
      • same as (*pp).x =9 only this is proper
  • self referential structures
  • if you don't use malloc calloc etc it is put on the stack not the heap
  • look in back of the book under IO
    • c library IO(buffered)
    • this is the buffer which input and output is written to
    • int getChar(void)
    • int putchar(int)
    • scanf
    • printf
  • file access
    • FILE
      • The way you create one is
        • FILE * fp
        • fp = fopen("filename", mode);
        • mode is
          • read write and append
          • a 2 character string
          • char*
        • instead of filename you can use
          • "rb"
          • "wb"
          • Ab"
          • "rt"
          • "wt"
          • "at"


 


 


 

//creating a structpoint//

--------------------

structpoint{

    int x;

    int y;


 

    }

---------------------------


 

structpoint p1;

p1.x = 5;

p1.y = 6;

------------

or


 

structpoint p1 = {5,6};

----------------------------------

or

structpoint{

int x;

int y;

}

p1;

p1.x = 5

p1.y = 6;

//you can make a new struct doing it this way

--------------------------------------

struct{

int x;

int y;

}

p1.x = 5;

p1.y = 6;

//cannot make a second struct doing it this way

---------------------------------------

typef unsigned int size_t;

typedef void (*_sighandler_t)(int)

--------------------------------------

typedef structpoint {

int x;

int y;

}

point;

/*now "point" is the name of a type

* it can have pint p1;

*instead of structpoint p1

*/

--------------------------------

/* self referential structures*/

struct listNode{

int value;

struct listNode* next;

}

--------------------------------

struct treeNode{

int value;

struct treeNode* left;

struct treeNode* right;

}

------------------------------------

or

--------------------------------------

typedef structTNode* TreePtr

typedef structTNode{

int value;

TreePtr left;

TreePtr right;

}TreeNode


 

-----------------------------------------

TreePtr root = (TreePtr)malloc(sizeof(TreeNode));         // - do not do this instead - sizeof(int) + 2*sizeof(TreePtr)

root->value = 5;

root -> right = (TreePtr)malloc(sizeof(TreeNode));

root -> right ->value=2;

root -> right->right =null;

root -> right ->left = null;

/*creates a binaryTree with root starting point at 5 pointing to a 2 on its right side that has no strings after it*/

--------------------

struct item{

double price;

char name[50];

}

item x1;

strcpy(x1,name, "Notebook");

---------------------------

struct item{

double price;

char* name;

}

item x1;

x1.name = "notebook";

-----------------------------------

fprintf(fp,...);

fscanf(fp,...);

fclose(fp);

ferror(fp);

intfeof(fp); //if you reached end of file on that file

fflush(fp);

fseek(fp,...);

fsetpos(fp,...);

--------buffered standard output under this line--

stdin

stdont

stderr

---------unbuffered under this line---


 

STDIN_FILENO         0

STDOUT_FILENO        1

STDERR_FILENO        2

--------------------------------------------------

#include <stdio.h>

#include <unistd.h>

int main(void)

{

printf("a");

write(1, "X", 1);

fprintf(stdout, "B");

write (1,"Y", 1);

printf("C");

write(1, "Z\n", 2);

printf("\n");

return 0;

/*output is

XYZ

ABC

this is becuase it's buffered

/*

}

                        

Tuesday, January 29, 2008

CSE2031 Lecture 7

void* ß malloc (int n)

int *p;

p = malloc (50 * sizeof(int));

Or

p = (int*) malloc(50*sizeof(int));

if((p=malloc(..) ) == null)

{

…exit(1)

}

free(p); //deallocate this space;

  • calloc enters 0's in memory for allocated space
  • go to man 3 malloc
    • talks about malloc calloc and realloc
    • realloc
      • allows you to resize memory partition previously allocated
  • arrays in C don't know how long they are

int x //declares an int

int f(int a , double b) // function that returns an int

int *f(int a, double b) //pointer to a unction that returns an int

int (*f)(int a, double b )//declares a function that takes parameters and returns an int


 


 


 


 


 


 


 


 


 

#include <stdlib.h>

#include <stdio.h>

#include <string.h>


 

int strCompare(const void *, const void *);

int intCompare(const void* p1, const void* p2);

int main(void)

{

char* A[] = {"30","3","20","2","0","5","10","1","40","4", "5"};

    for (i = 0;i<11;i++)

{

printf("%s ", A[i[);

}

putchar('\n');

qsort(A, sizeof(A)/sizeof(char *), sizeof(char *), strCompare);

return 0;

}

int strCompare(const void*p1,const void*p2)

{

int n = strcmp(*(char**)p1, *(char**)p2); //

if (n<0) return -1;

if (n>0) return 1;

return 0;

}

int intCompare(const void*p1, const void*p2)

{

int n1 = atoi(*(char**)p1);

int n2 = atoi(*(char**)p2); // atoi casts string to integer

if (n1<n2) return -1;

if (n1>n2) return 1;

}


 

(A, ... , cmp)

//int cmp(const void *p1, const void *p2)

//{int n1 =

int n2 =

if(n1<n2) return -1;

if(n1>n2) return 1;

return 0;


 


 

c struct

  • struct point {int x, int y};
    • point is the structure tag

CSE2011 Lecture 8

Loop invariants

  • What is the loop invariant
    • In general it is an extremely difficult question to answer. It contains the essential difficulty in programming
    • Fundamentally it is the following
      • LI = totalWork = workToDo + workDone
    • Question a: does the loop terminate?
    • Question b: is the postcondition of OP true at loop end

Loop Design

  • Find the loop invariant
  • After consulting an oracle we have determined that the following is an appropriate loop invariant
    • This is the create part of programming
  • Question 1
    • Make the loop invariant true at the start
  • Question 2
    • Is the loop invariant still true after operation 2 is executed?
    • After operation2 show li first part is true
    • See effect of moving data from workToDo to workDone while maintaining the invariant

EATS1011 Lecture 8

Clouds

  • Clouds to fall but then they fall into warmer air and evaporate
  • CCN: 100%
    • Cloud condensation Nuclei (CCN)
  • Newton's first law
    • The droplet of radius r
    • The droplet's going down
    • And friction of particles in the air
    • Eventually balance out
    • Friction force
      • 6πR(eta) V
        • Eta is viscosity (missing symbol)
    • Gravitational force
      • M*g
        • M ass of the droplet
        • G ravity
        • = 4/3πR3
    • These two forces equal each other out
    • Get formulas from website
    • This only applies to 'small' droples (< 100microns)
    • Terminal Velocity




    • VT = 6x103 R(m) m/s (R> 100 mm)
  • Condenstation -> growth
    • 1/R
  • 1) collision and coalescence
    • Warm
  • 2) bergeon process
    • Mixed phase clouds
      • (liquid water + ice)
    • The difference in vapour pressure drives the growth of the droplets
  • Size spectrum
    • 1 micron -> 5 microns -> 10 microns – 15 microns – 50 microns
    • The small ones fall slower than the large ones
    • The large one sweep up the smaller ones under them
      • Until the droplet gets even bigger and falls faster
      • If there are enough small particles you can see how we get very large droplets

Thursday, January 24, 2008

CSE 2031 Lecture 6

Arrays and pointers

  • An array name by itself is
    • An address
    • A pointer value
  • A pointer is
    • A variable taking addresses as values
  • An array name is
    • A particular fixed address
    • Like a constant pointer
  • When an array is declared, the compiler allocates
    • A base address
      • The address of element 0
  • And sufficient memory allocation for the rest of the elements

Array indexing and pointer arithmetic

#define MAXSIZE 1024

int A[MAXSIZE], *p;

/*

*space allocated for A

* but p – has not been given a value , even if it did here wouldn't necessarily be any space allocated *where it pointed

*/

Equivalent Statements

  • P = A;
  • P = A+I;
  • P = &A[0];
  • P=&A[i];
  • P[0]
    • is the same as saying *p
  • p[3]
    • is the same as saying *(p+3)

Summing the Array

  • 4 forms
  • 1

    sum =0;

    int i;

    for (i=0; i<maxSize; i++)

    sum += A[i];


     

  • 2

sum = 0;

for(p=A; p<&A[MAXSIZE];p++)

sum+= *p;

  • 3

sum = 0;

For(i=0;i<MAXSIZE;i++

sum += *(A+i);

  • 4

Sum = 0;

P=A;

For(i=0 i<MAXSIZE;i++)

Sum += p[i]; /*no dereferencing*/

  • Practice adding pointers and casting them
  • When you minus the two you get how many blocks of allocated memory exist between them
  • If you cast them and minus them you get the mem address casted to ints then you get the difference between that

Arrays as function parameters

  • In a function header
    • An array isn't declared w/ a fixed size in a function header
    • Int A[] is equivalent to int *A
      • This ONLY applies to a function parameter
    • Otherwise Int A[] is is NOT equivalent to int *A
      • Int *A; creates a pointer variable
      • Int A[] creates a constant pointer and no storage

Pointers and strings

  • Strings are arrays of char and are ended with \0
    • \0 is a null character
  • "ABC"
    • Type is char*
    • Value is address of the 'A'
  • Char word[] = "xyz"
    • Is the same as char word[] = {'x','y','z','\0'};
  • Char *p = "xyz";
    • Word is an array of length 4.
    • P is a pointer and points (for now) to an array with 4 elements
    • P can change reference
    • *p doesn't allocate new space

Dynamic Memory Allocation

  • Memory allocated while the program is running
  • Stack
    • When there is a function call there are parameters and local variables
    • Space set aside to hold the values for returns when functions are called
      • Stacks grow during recursion
      • Goes from the top down
      • LIFO
    • A stack grows and shrinks automatically
  • Heap
    • Declares space and the space remains allocated

Malloc

  • Void *malloc ( size_T n) /* memory allocation*/
    • Returns pointer to n bytes
    • Parameter is an integer type
      • Signed or unsigned
    • Sets aside an amount of space
    • Set aside contiguously , like an array
    • What is returned is a pointer to the space allocated
    • If space cannot be allocated a null pointer is returned
    • The storage is uninitialized
      • Not necessarily emptied space
    • Returns NULL if it can't be done
  • Void *calloc (size_t n, size_t element_size)
    • Allocate enough space for this many elements that take 'so much space'

Algorithm assessment

  • Is the algorithm running in constant time?
    • Runs the same amount of time no matter when 'n' is
    • O(1)
      • No loops or constant time loops
  • Linear time
    • Does the problem run exactly proportional to the size of 'n'?
    • Dominant single loop dependant linearly on n
  • Logarithmic
    • The algorithm divides the size of the problem by a constant
      • Runs in O(log n)
        • Dominant single lop is a divide by 2 on each iteration

Assertions

  • Boolean expressions or predicates that evaluate to true or false
  • In a program they express constraints on the state that must be true at that point
  • Associate with
    • Individual program statements
    • Functions
    • Classes
  • Specify clearly, precisely and succinctly
    • What is expected and guaranteed by each component
      • Class function and statement
    • The essence of documentation
    • Essential for debugging
    • Aids in fault tolerance
  • Result
    • Result of a query but only in ensure assertions
  • Current
    • @ Current object
  • Void
    • Not attached
  • Name
    • Value of the variable name before a routine starts
  • Name'
    • Value of the name after a routine terminates
    • Alternate name 'old name' instead of Name'
  • **study textual notation**
    • From online notes, cannot type all this

Tuesday, January 22, 2008

CSE 2031 Lecture 5

void makeDouble(int* x)

{

    *x = 2* *x;

}


 

* modifies a pointer

This in English is makeDouble takes an integers pointer

Then the integers pointer is modified.

An '&' sign is a pointer. int I, *p; /* means that there is an integer I and an integer memory reference *p;

An expression has a type and value.

*(r=&j) *= *p

**p dereferences p


 

Pointer to void

  • Why do pointers have types?
    • So we can dereference them

Eats 1011 Lecture 6

ITCZ - intertropical Convergence Zone

ERBE – Earth Radiation Budget Experiment

  • Designed to study the radiative energy
  • Measures radiation coming from the atmosphere

Tropics

  • Solar heating is greater than IR cooling

Polar Regions

  • Solar heating is less than IR cooling

Heat transfers between the two to stop the earth from getting really hot in some areas and really cold in others


 

Water Vapour in the Atmosphere

  • Mixing ratio
    • Troposphere is between 10-2 to 10-5 by volume or mass with most in the lower troposphere
    • Global average ~2.5*10-3
    • Stratosphere 4*10-6 by volume
  • Latent Heat
    • Energy is required/released for a phase change
    • Heat storage when liquid converts to vapour
    • Heat release when vapour turns to water
      • Lv – vaporization – 2.5 * 106 J/Kg
      • Lf – fusion / freezing – 3.3*105
      • Ls – sublimation – Lu + Lf – 2.8*106
        • Energy required / released when 1Kg of material changes state
  • To calculate the amount of energy required for evaporation
    • Need mass of water

      • 2cm = 0.02m rain (over each m2)
      • Density water, pw = 1000kg/m3
      • Mass = 20kg/m2





      • Mean water mixing ratio ~
        • Mass water =
      • Removal rate is estimated from the globally average rainfall ~ 1m / year
      • This is equivalent to about
      • Mass over 1m2 ~ /m2
      • = 1000 kg/m2
      • Turnover time

tresidence = (25kg/m2) / (1000 kg/m2 * year)

Sunday, January 20, 2008

Delete me

Thursday, January 17, 2008

CSE 2031 Lecture 4

Strings

  • strlen(s)
    • returns length
  • strcmp(s,t)
  • returns positive if s>t, negative if s<t, and 0 if they are equal.
  • strcat(s,t)
    • concatenates t onto s
      • changes string s
    • looks or \o and contatenates at that spot

#include <stdio.h>

Int main(void)

{

char s1[] = {'H','e','l','l','o','\o'};

char s2[4];

printf("Address of s1 is %p\n", s1);

printf("address of s2 is %p\n", s2);

printf("Enter a line: ");

fgets(s2, sizeof(s2), stdin);/* bolded represent extras for using fgets*/

printf("%s\n", s2);

printf("%s\n", s1);

return 0;

}


 

  • Fgets is the new one that works better, if you use just gets you will run into problems with memory over runs
  • Where s1 in this example can be overwritten by s2 if the user input is long enough
  • Look up input and output in textbook
  • With fgets it will only take in the amount of characters assigned after the first comma
  • However if less than the specified amount is passed and the enter key is pushed, the new line character will count as 1 char

Pointers

int n = 5;

int *p;

p = &n

printf("%d\n", *p);

printf("%d\n", n);


 


 

  • *p = 7;
    • Changes whatever value P was addressing to 7

If n = 5, and you said this before printing, it would print 7