03 C and Datastructs
03 C and Datastructs
03 C and Datastructs
Instructor:
Franz Franchetti
Scope of C in 18-613
Bootcamp: Linux and Windows
Basic data types and functions
Structures, arrays, etc.
C Standard Library
Linux/POSIX Libraries
Language Extensions
Final thoughts
Scope of C in 18-613
Bootcamp: Linux and Windows
Basic data types and functions
Structures, arrays, etc.
C Standard Library
Linux/POSIX Libraries
Language Extensions
Final thoughts
char 1 1 1
short 2 2 2
int 4 4 4
long 4 8 8
float 4 4 4
double 8 8 8
pointer 4 8 8
Bit-Level Operations in C
Operations &, |, ~, ^ Available in C
Apply to any “integral” data type 0 0 0000
long, int, short, char, unsigned 1 1 0001
2 2 0010
View arguments as bit vectors 3 3 0011
4 4 0100
Arguments applied bit-wise 5 5 0101
Examples (Char data type) 6 6 0110
7 7 0111
~0x41 → 0xBE 8 8 1000
~0100 00012 → 1011 11102
9 9 1001
A 10 1010
~0x00 → 0xFF B 11 1011
~0000 00002 → 1111 11112 C 12 1100
D 13 1101
0x69 & 0x55 → 0x41 E 14 1110
0110 10012 & 0101 01012 → 0100 00012 F 15 1111
0x69 | 0x55 → 0x7D
0110 10012 | 0101 01012 → 0111 11012
Casting Surprises
Expression Evaluation
If there is a mix of unsigned and signed in single expression,
signed values implicitly cast to unsigned
Including comparison operations <, >, ==, <=, >=
Examples for W = 32: TMIN = -2,147,483,648 , TMAX = 2,147,483,647
Constant1 Constant2 Relation Evaluation
0 0 0U
0U == unsigned
-1 -1 00 < signed
-1 -1 0U
0U > unsigned
2147483647
2147483647 -2147483647-1
-2147483648 > signed
2147483647U
2147483647U -2147483647-1
-2147483648 < unsigned
-1 -1 -2
-2 > signed
(unsigned)-1
(unsigned) -1 -2
-2 > unsigned
2147483647
2147483647 2147483648U
2147483648U < unsigned
2147483647
2147483647 (int)2147483648U
(int) 2147483648U > signed
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 11
Carnegie Mellon
Integer C Puzzles
x < 0 ⇒ ((x*2) < 0)
ux >= 0
x & 7 == 7 ⇒ (x<<30) < 0
ux > -1
x > y ⇒ -x < -y
x * x >= 0
Initialization x > 0 && y > 0 ⇒ x + y > 0
int x = foo(); x >= 0 ⇒ -x <= 0
x <= 0 ⇒ -x >= 0
int y = bar();
(x|-x)>>31 == -1
unsigned ux = x; ux >> 3 == ux/8
unsigned uy = y; x >> 3 == x/8
x & (x-1) != 0
Representing Strings
char S[6] = "18213";
Strings in C
Represented by array of characters
Each character encoded in ASCII format x86-64
Standard 7-bit encoding of character set
31
Character “0” has code 0x30 38
– Digit i has code 0x30+i 32
String should be null-terminated 31
Final character = 0
33
Compatibility 00
Byte ordering not an issue
Floating Point in C
C Guarantees Two Levels
float single precision
double double precision
Conversions/Casting
Casting between int, float, and double changes bit representation
double/float → int
Truncates fractional part
Like rounding toward zero
Not defined when out of range or NaN: Generally sets to TMin
int → double
Exact conversion, as long as int has ≤ 53 bit word size
int → float
Will round according to rounding mode
Functions
Functions
have return value, can be ignored
Procedures: no return value
void x();
Call by value/by reference
use of pointers, when to copy
Recursion: nothing special
Declaration and definition
Modifiers: __inline, __naked , …
Variable length arguments:
printf, scanf,…
In your own functions:
int sum(int n, …)
va_arg()
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 18
Carnegie Mellon
Scope of C in 18-613
Bootcamp: Linux and Windows
Basic data types and functions
Structures, arrays, etc.
C Standard Library
Linux/POSIX Libraries
Language Extensions
Final thoughts
Array Access
Basic Principle
T A[L];
Array of data type T and length L
Identifier A can be used as a pointer to array element 0: Type T*
int val[5]; 1 5 2 1 3
x x+4 x+8 x + 12 x + 16 x + 20
Reference Type Value
val[4] int 3
val int * x
val+1 int * x+4
&val[2] int * x+8
val[5] int ??
*(val+1) int 5
val + i int * x+4i
Mem[pgh+20*index+4*digit] Mem[Mem[univ+8*index]+4*digit]
N X N Matrix #define N 16
typedef int fix_matrix[N][N];
Code /* Get element A[i][j] */
int fix_ele(fix_matrix A,
Fixed dimensions size_t i, size_t j)
Know value of N at {
compile time return A[i][j];
}
#define IDX(n, i, j) ((i)*(n)+(j))
Variable dimensions, /* Get element A[i][j] */
explicit indexing int vec_ele(size_t n, int *A,
Traditional way to size_t i, size_t j)
{
implement dynamic
return A[IDX(n,i,j)];
arrays }
A1 Allocated pointer
Unallocated pointer
A2
Allocated int
Unallocated int
A1
A2/A4
A3
Allocated pointer
Unallocated pointer
Allocated int
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Unallocated int 26
Carnegie Mellon
A2/A4
A3
A5
double fun(int i) {
volatile struct_t s;
s.d = 3.14;
s.a[i] = 1073741824; /* Possibly out of bounds */
return s.d;
}
Union
Allocate according to largest element
Can only use one field at a time
union U1 {
char c;
int i[2]; c
double v; i[0] i[1]
} *up;
v
struct S1 { up+0 up+4 up+8
char c;
int i[2];
double v;
} *sp;
int x; double x;
int y; p2() {} Writes to x in p2 might overwrite y!
p1() {} Evil!
Global Variables
Avoid if you can
Otherwise
Use static if you can
Initialize if you define a global variable
Use extern if you reference an external global variable
Scope of C in 18-613
Bootcamp: Linux and Windows
Basic data types and functions
Structures, arrays, etc.
C Standard Library
Linux/POSIX Libraries
Language Extensions
Final thoughts
int main() {
fprintf(stdout, "Hello, world\n");
}
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 40
Carnegie Mellon
malloc Example
#include <stdio.h>
#include <stdlib.h>
void foo(int n) {
int i, *p;
Scope of C in 18-613
Bootcamp: Linux and Windows
Basic data types and functions
Structures, arrays, etc.
C Standard Library
Linux/POSIX Libraries
Language Extensions
Final thoughts
Process Control
Spawning processes
Call fork
One call, two returns
Process completion
Call exit
One call, no return
Reaping and waiting for processes
Call wait or waitpid
Loading and running programs
Call execve (or variant)
One call, (normally) no return
Signals
void sigint_handler(int sig) /* SIGINT handler */
{
printf("So you think you can stop the bomb with ctrl-c, do you?\n");
sleep(2);
printf("Well...");
fflush(stdout);
sleep(1);
printf("OK. :-)\n");
exit(0);
}
int main()
{
/* Install the SIGINT handler */
if (signal(SIGINT, sigint_handler) == SIG_ERR)
unix_error("signal error");
return 0;
}
Unix I/O
Elegant mapping of files to devices allows kernel to export
simple interface called Unix I/O:
Opening and closing files
open()and close()
Reading and writing a file
read() and write()
Changing the current file position (seek)
indicates next offset into file to read or write
lseek()
B0 B1 • • • Bk-1 Bk Bk+1 • • •
Example:
int clientfd = Socket(AF_INET, SOCK_STREAM, 0);
Scope of C in 18-613
Bootcamp: Linux and Windows
Basic data types and functions
Structures, arrays, etc.
C Standard Library
Linux/POSIX Libraries
Language Extensions
Final thoughts
52
Carnegie Mellon
Compiler Options
53
Carnegie Mellon
#include <stdio.h>
struct ieee754d {
unsigned int s: 1;
unsigned int exp: 11;
unsigned int frac: 52;
};
int main() {
struct ieee754d d = {0U, 0U, 33729U};
d.exp = 113U;
printf("%e", (double *)(&d));
return 0;
}
54
Carnegie Mellon
8 16-bit integers
4 32-bit integers
4 single-precision floats
2 double-precision floats
1 single-precision float
1 double-precision float
55
Carnegie Mellon
57
Carnegie Mellon
printf("%d\n", dst)
59
Carnegie Mellon
60
Carnegie Mellon
int main()
{
...
// Kernel invocation with one block of N * N * 1 threads
int numBlocks = 1;
dim3 threadsPerBlock(N, N);
MatAdd<<<numBlocks, threadsPerBlock>>>(A, B, C);
...
}
61
Carnegie Mellon
Scope of C in 18-613
Bootcamp: Linux and Windows
Basic data types and functions
Structures, arrays, etc.
C Standard Library
Linux/POSIX Libraries
Language Extensions
Final thoughts
62
Carnegie Mellon
https://courses.ece.cmu.edu/18645
http://www.ece.cmu.edu/~franzf/papers/gttse07.pdf
https://www.inf.ethz.ch/personal/markusp/teaching/18-645-CMU-spring08/course.html 63
Carnegie Mellon
https://www.cs.cmu.edu/afs/cs.cmu.edu/academic/class/15418-s18/www/schedule.html
64
Carnegie Mellon
#include<fcntl.h>
#include<unistd.h>
#include<termios.h>
#include <sys/time.h>
#include <sys/mman.h>
# define L } if(!i -- ){
struct timeval F,G; struct termios H,U={ T} ; enum{ N=64,a=N<<7,b=a-1,c=a*32,d
=c-1, e=c/ 2,f= a*2, g=a/2,h =g/2,j =h/ 2,Q=V*j*5} ; char*s=P,K,M;
int* p, l[ a] ,m,n,J,o=A, O=j,E,R,i,k,t,r,q,u,v,w,x,y,z
,B,C, *D,Z ;int main (){ for(D=mmap(D,4*Q,3,W,open(I,2 ),K); *s; o
++[ l]=k|=* s++%N){ k=* s++%N<<12; k|=*s++% N*N; } tcgetattr(q,& H); tcsetattr
(y,2, &U); for( fcntl(B,4,4); ; o&=b){ if(k& c){ q=- --k%N; if(!q)
k-=c ;i =k /N&7; { L L if(J&1) m+= t; J|=m%N*c; J/=2; m
/= 2; if(! q&&r ^n){ m^=d; J^= d; n=0; } L L J+=J; J|=m>=0; if(q){
m+=m; m|=J/c; m+=m<0?t:-t; } else{ m+=(m<0)*t; if(r)m^=d; if(n^r)J^= d; n=0; }
L if( (m^2 *m)/ e%2) k&=d; else{ J+=J; m+=m; m|=J/c; } L m|=n*c; J
|= m %N *c ;m /=2; J /=2; L m+=m; J+=J; J|=n; m|=J/c; L
m+=m; m|=n ; } J&=d ; } else{ i=k/f; t=i?k&b:16; p=l+t; if(k&a)p=
l+((*p+=13>i&&7<t&&16>t)&b); { L i=1; L*p=m; L*p++=o|n*e; o=p-l; L*p=0; L m=*p
; L m ^=*p ; L t=m; m +=*p; m+=d<m ; n|=((m^t)& (m^*p))/e; L m+=*p
; n=m/c; L k=*p; if( !Z||k/f-8) /*$ %*/ continue ; k=-k
; L++*p; o +=!(*p&=d) ; L m&=*p; L if(m!=*p)++ o; L o=p -l; L if(
k&a)n=m/e; if(k&g)J= 0; r=k&h&&m&e; if(k&j)J|=m; else if(r)m^=d; if(k&512)m=0;
i=k/N &7; { L if(k &4)J ^=d; if(k&2)m|=J; if (k&1 )m|= q; }
else { if(k%N)k += c; { L t =o ++[ l] ; if(r
)J^=d; L L t=o++[l]; if(r )J^=d; m-=t; if(m>=0 ){ k -=c; n=1;
++o; } } i=2; } L if(Z)k=-1; else{ if(k&8)m=0; t=r=0; i=k/N%N; if(i==27){ if(k
&2)u=v=w=Z=0; } if (i==57){ i=k/16&3; { L w =1; if(k&1)x =0; if(k&
2) { t= z/N; t= t/80*/*/*/100+t% 80; r=0 ; while(t) { r
+=t%10*w; t/= 10;w <<=4; } m|=r; } if(k&4){ r=m ; t=0; while (r) {
t+=r%16*w; w*=10; r>>=4; } r=t/100; t%=100; if(V<=r||79<t)x|=c/8; else z=(r*80
+t)*N ; } w=0; L if(k& 1&&x &(e|g) )++o; if(k& 2)m|=x |y;if
(k&4 )C =- m&65535; L if( k&1 )x=y=0; if (k&2
)B=m; if ( k&4) { y^=m&(h|j| j/2); if(y&j ){ y^=j;x|=g ; do{
B&=b; if(y&j/2)z[D]=B[l]; else B[l]=z[D]; ++z; z%=Q; ++B; } while(-- C); } } }
x%=e; if(x /a)x |=e; if(x&(e|g)&&y&h)u|=c ; else u%=c; L if(
k&1) t= h; if (k&2 )r= e; if( k&4){ r=j; u&=~
h ; } if(k &16) Z=f* 2; L L L t=f; if(k&2 )m|=M|Y; if( k&4)m
|=u|v; L t=a; if(k&4){ K=m&~Y; write(1,&K,1); u|=t; t=0; } } i=2; if(t){ if(k&
1&&u&t)++ o; if(k&2)u &=~ t; } if( r){ if(k&32) w=r; else v&=~r; }
} L if(k&a)m=k; else { t=0; if( k & N)t |= m/e%2; if(k&
128)t|=!m; if(k&256)t |= n; if( k& 512 )t=!t; o +=t; if(k& h)n =0;
if(k&g)m=0; if(k&1)m^=d; if(k&2)n^=1; if(k&4)m|=S; if(k&8){ m|=n*c; m+=m; if(k
& j)m +=m; m|=m /a/N ; n=m/c; } if(k&16){ m|=n*c; m|=m *2%N*
c; m /= 2; if (k&j) m/=2; n=m/c; } if (k &32)
{ if( Z)k= -1 ; else break; } } } } n&=1; if(k<c) { m &= d;
o &=b; if(!R--){ if (~u&f &&read(0, &M,1)>0){ if(X&& M== X)break; R=0; u|=f; }
gettimeofday(&G,0); G.tv_usec/=16667; if(G.tv_sec>F.tv_sec||F.tv_usec<G.
tv_usec){ F=G; if(v&j){ p=l+7; ++*p; *p&=d; if(!*p)u|=h; } R=0; } if
(!R){ E=O/4; O=4; } O+=R=E; } if(!++k||(v&e&&u)){ *l=o|n*e|Z;v%=
e; o=1+!k; Z=0; } v|=w; w=0; k=o++[l]; } }tcsetattr(w,1,&H); } https://www.ioccc.org/2018/mills/prog.c
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 65
Carnegie Mellon
https://en.wikipedia.org/wiki/Duff%27s_device
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 66