72
Embedded Software TI2725C 2C i 2. C programming Koen Langendoen b dd dS f G EmbeddedSoftware Group

Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Embedded SoftwareTI2725‐C

2 C i2. C programming

Koen Langendoenb dd d S f GEmbedded Software Group

Page 2: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C crash course For Java programmers

Main differences

Common pitfalls

// Language + tools // next lecture

L i b d i Learning by doing Online – Weblab

Hands on – supervised labs Hands on  supervised labs

2

Page 3: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C for Java Programmers*C for Java Programmers

Henning SchulzrinneDept. of Computer Science

Columbia University

*Selection and editing by Koen Langendoen

Page 4: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C historyy

C Dennis Ritchie in late 1960s and early 1970s systems programming language

make OS portable across hardware platformsil f l li i ld b i i not necessarily for real applications – could be written in

Fortran or PL/I

C++ Bjarne Stroustrup (Bell Labs), 1980s object-oriented features

JavaJava James Gosling in 1990s, originally for embedded systems object-oriented, like C++ ideas and some syntax from C

Henning Schulzrinne Advanced Programming 4

ideas and some syntax from C

Page 5: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Aside: “generations” and abstraction levelsabstraction levels

Binary, assembly Fortran, Cobol PL/I, APL, Lisp, …p C, Pascal, Ada C++, Java, Modula3, , Scripting: Perl, Tcl, Python, Ruby, … XML-based languages: CPL, VoiceXMLXML based languages: CPL, VoiceXML

Henning Schulzrinne Advanced Programming 5

Page 6: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Why learn C (after Java)?Why learn C (after Java)? Both high-level and low-level language

OS: user interface to kernel to device driver Better control of low-level mechanisms

memory allocation, specific memory locations

Ideal for embedded memory allocation, specific memory locations

Performance sometimes better than Java usually more predictable

Most older code is written in C

systems

Most older code is written in C Being multi-lingual is good!

B t But,…. Memory management responsibility Explicit initialization and error detection More room

for errors

Henning Schulzrinne Advanced Programming 6

generally, more lines for same functionality for errors

Page 7: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Prog. language popularity

Page 8: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C vs. JavaJava Cbj t i t d f ti i t dobject-oriented function-oriented

strongly-typed can be overridden

pol mo phism (+ ) e limited (intege /float)polymorphism (+, ==) very limited (integer/float)

classes for name space (mostly) single name space

macros are external, rarely used

macros common (preprocessor)

layered I/O model byte-stream I/O

Henning Schulzrinne Advanced Programming 8

Page 9: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C vs. JavaJava C

t ti f ti ll ( ll f )automatic memory management

function calls (malloc, free)

no pointers (only pointers (memoryno pointers (only references)

pointers (memory addresses) common

by-reference, by-value by-value parametersexceptions, exception handling

if (f() < 0) {error}OS signals

concurrency (threads) library functions

Henning Schulzrinne Advanced Programming 9

Page 10: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C vs. JavaJava Cl th flength of array on your ownstring as type just bytes (char []), with 0

endenddozens of common libraries OS-defined

Henning Schulzrinne Advanced Programming 10

Page 11: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Java programp g

collection of classes class containing main method is starting class running java StartClass invokes StartClass.main method

JVM loads other classes as required

Henning Schulzrinne Advanced Programming 11

Page 12: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C programp g

collection of functions one function – main() – is starting function running executable (default name a.out) starts g ( )

main function typically, single program with all user code

linked in – but can be dynamic libraries (.dll, .so)

Henning Schulzrinne Advanced Programming 12

Page 13: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C vs. Javapublic class hello{{

public static void main (String args []) {System.out.println(“Hello world”);

}}}

#include <stdio.h>

int main(int argc, char *argv[]){{puts(“Hello world”);return 0;

}

Henning Schulzrinne Advanced Programming 13

}

Page 14: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Simple examplep p

#include <stdio h>#include <stdio.h>

void main(void){{

printf(“Hello World.\n\t and you !\n”);/* print out a message */

return;}

$ a.outHello World.

and you !$

Henning Schulzrinne Advanced Programming 14

$

Page 15: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Dissecting the example #include <stdio.h>

include header file stdio.hinclude header file stdio.h # lines processed by pre-processor No semicolon at end Lower-case letters only – C is case-sensitive

void main(void){ … } is the only code executed printf(“ /* message you want printed */ ”);

\n = newline, \t = tab, \ in front of other special characters within printf. printf(“Have you heard of \”The Rock\” ? \n”);

Henning Schulzrinne Advanced Programming 15

Page 16: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Executing a C programg p gint main(int argc, char *argv[])

argc is the argument count argv is the argument vector array of strings with command-line arguments

the int value is the return value convention: 0 means success, > 0 some error can also be declared as void (no return value)

Henning Schulzrinne Advanced Programming 16

Page 17: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Simple example – take 2p p

#include <stdio h>#include <stdio.h>

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

printf(“Hello World.\n”);for(int i=0; i<argc; i++)

printf(“\t arg %d: %s\n”, i, argv[i]);p g greturn 0;

}

$ a.outHello World.

arg 0: a.out$

Henning Schulzrinne Advanced Programming 17

$

Page 18: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Executing a C programg p g

Name of executable + space-separated arguments

$ a.out 1 23 ‘third arg’

argc argv

4

“a.out” “1” “23” “third arg”

Henning Schulzrinne Advanced Programming 18

Page 19: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Executing C programsg p g

Scripting languages are usually interpreted perl (python, Tcl) reads script, and executes it sometimes, just-in-time compilation – invisible to user

Java programs semi interpreted: Java programs semi-interpreted: javac converts foo.java into foo.class not machine-specificnot machine specific byte codes are then interpreted by JVM

C programs are normally compiled and linked: gcc converts foo.c into a.out a.out is executed by OS and hardware

Henning Schulzrinne Advanced Programming 19

Page 20: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Executing C programsg p g

l resultsperlx.pl

data

results

javac javax.java

args

gcc a.outx.c

Henning Schulzrinne Advanced Programming 20

Page 21: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

The C compiler gccp g

gcc invokes C compiler gcc translates C program into executable for

some target default file name a.out also “cross-compilation”$ gcc hello.c$ a.outHello, World!Hello, World!

Henning Schulzrinne Advanced Programming 21

Page 22: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

gccg

Behavior controlled by command-line switches:

-o file output file for object or executable

-Wall all warnings – use always!-Wall all warnings – use always!

-c compile single module (non-main)

-g insert debugging code (gdb)

-p insert profiling code

-l library

-E preprocessor output only

-std=c99 C++ style comments, local vars in for loops, …

Henning Schulzrinne Advanced Programming 22

Page 23: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Using gccg g

Two-stage compilation pre-process & compile: gcc –c hello.c

link: gcc –o hello hello.o

Linking several modules:gcc –c a.c a.o

bgcc –c b.c b.ogcc –o hello a.o b.o

Using math library Using math library gcc –o calc calc.c -lm

Henning Schulzrinne Advanced Programming 23

Page 24: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Error reporting in gccp g g

Multiple sources preprocessor: missing include files parser: syntax errors assembler: rare linker: missing libraries

Henning Schulzrinne Advanced Programming 24

Page 25: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Error reporting in gccp g g

If gcc gets confused, hundreds of messages fix first, and then retry – ignore the rest

gcc will produce an executable with warnings don’t ignore warnings – compiler choice is often

not what you had in mind

Does not flag common mindos Does not flag common mindos if (x = 0) vs. if (x == 0)

Henning Schulzrinne Advanced Programming 25

Page 26: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C preprocessorp p

The C preprocessor (cpp) is a macro-processor which manages a collection of macro definitions

d C d f reads a C program and transforms it Example:

#define MAXVALUE 100#define check(x) ((x) < MAXVALUE)if (check(i) { }

const int MAXVALUE = 100;

int check(int x) {if (check(i) { …}

becomesif ((i) < 100) {…}

return x < MAXVALUE;}

Henning Schulzrinne Advanced Programming 26

Page 27: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C preprocessorp p

Preprocessor directives start with # at beginning of line: define new macros (don’t try this at home! )

f l h C d ( ll d f ) input files with C code (typically, definitions) conditionally compile parts of file

gcc E shows output of preprocessor gcc –E shows output of preprocessor Can be used independently of compiler

Henning Schulzrinne Advanced Programming 27

Page 28: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C preprocessor –file inclusionp p#include “filename.h”#i l d <fil h>#include <filename.h>

inserts contents of filename into file to be compiled “filename” relative to current directoryfilename relative to current directory <filename> relative to /usr/include gcc –I flag to re-define default import function prototypes (cf. Java import) Examples:

#include <stdio.h>#include “mydefs.h”#include “/home/alice/program/defs.h”

Henning Schulzrinne Advanced Programming 28

Page 29: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C preprocessor – conditional compilationcompilation

#if expressioncode segment 1code segment 1#elsecode segment 2#endif preprocessor checks value of expression if true, outputs code segment 1, otherwise code segment 2 machine or OS-dependent code can be used to comment out chunks of code – bad!

#define OS linux…#if OS == linux#if OS linuxputs(“Linux!”);

#elseputs(“Something else”);

# dif

Henning Schulzrinne Advanced Programming 29

#endif

Page 30: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C preprocessor - ifdefp p

For boolean flags, easier:#ifdef namecode segment 1#elsecode segment 2#endif

preprocessor checks if name has been preprocessor checks if name has been defined #define USEDB

if so, use code segment 1, otherwise 2

Henning Schulzrinne Advanced Programming 30

Page 31: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C languageg g

Data model simple, low-level

Control structuresControl structures syntax quite similar to Java sequencing: ;

consistent indentationplease!

grouping: {...} selection: if, switch iteration: for, while operators: =, ==, +=, ++, &&, &

Henning Schulzrinne Advanced Programming 31

Page 32: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Numeric data typesyptype precisiontype precision #include <stdint.h>

char 8 bitsshort ≥ 16 bitschar 8 bits int8_tshort ≥ 16 bits int16_tint ≥ 16 bitslong ≥ 32 bitsint ≥ 16 bits int32_tlong ≥ 32 bits int64_tlong long ≥ 64bitsfloat ≥ 32 bitsd bl 6 b

long long ≥ 64bits int128_tfloat ≥ 32 bits IEEE 754 single prec.d bl 6 b d bldouble ≥ 64 bits

Architecture dependent

double ≥ 64 bits IEEE 754 double prec.

preferred

Henning Schulzrinne Advanced Programming 32

Architecture dependent preferred

Page 33: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Unsigned integersg g

Also, unsigned versions of integer types e.g., unsigned short, uint16_t

same bits, different interpretation shift right (>>) with(out) sign extension

((i t8 t)0 FF) >> 4 0 FF thou shalt ((int8_t)0xFF) >> 4 == 0xFF ((uint8_t)0xFF) >> 4 == 0x0F

overflow is undefined for signed ints, but

thou shalt avoid

unsignedsg ,wrap-around for unsigned ints ((uint8_t)0xFF) + 1 == 0x00

Henning Schulzrinne Advanced Programming 33

Page 34: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Type conversion

#i l d < tdi h>

yp

#include <stdio.h>void main(void){int i,j = 12; /* i not initialized, only j */j y jfloat f1,f2 = 1.2;

i = (int) f2; /* explicit: i <- 1, 0.2 lost */f1 = i; /* implicit: f1 < 1 0 */f1 = i; /* implicit: f1 <- 1.0 */

f1 = f2 + (float) j; /* explicit: f1 <- 1.2 + 12.0 */f1 = f2 + j; /* implicit: f1 <- 1.2 + 12.0 */

}

Henning Schulzrinne Advanced Programming 34

Page 35: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Explicit and implicit conversionsp p

Implicit: e.g., s = i + c Promotion: char -> short -> int -> … If one operand is double, the other is made double

If either is float, the other is made float, etc.

Explicit: type casting – (type) Almost any conversion does something – but

not necessarily what you intended

Henning Schulzrinne Advanced Programming 35

Page 36: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Type conversionypint x = 100000;h tshort s;

s = x;printf(“%d %d\n”, x, s);

100000 -31072100000 31072

Henning Schulzrinne Advanced Programming 36

Page 37: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

C – no booleans

C doesn’t have booleans Emulate as int or char, with values 0 (false)

and non-zero (true) Allowed by flow control statements:

if (n = 0) {printf(“something wrong”);p ( g g )

}

Assignment returns zero -> false

Henning Schulzrinne Advanced Programming 37

Page 38: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

User-defined typesyp typedef gives names to types:

typedef short int smallNumber;typedef unsigned char byte;

i 100typedef char String[100];

smallNumber x;byte b;String name;

Henning Schulzrinne Advanced Programming 38

Page 39: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Defining your own booleang ytypedef char boolean;#d fi FALSE 0#define FALSE 0#define TRUE 1

Generally works, but beware:Generally works, but beware:check = x > 0;if (check == TRUE) {…}

If is positive check will be non zero but If x is positive, check will be non-zero, but may not be 1.

Henning Schulzrinne Advanced Programming 39

Page 40: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Enumerated typesyp Define new integer-like types as enumerated types:

typedef enum {Red, Orange, Yellow, Green, Blue, Violet

} Color;enum weather {rain, snow=2, sun=4};

look like C identifiers (names) are listed (enumerated) in definition are listed (enumerated) in definition treated like integers

can add, subtract – even color + weather can’t print as symbol (unlike Pascal) but debugger generally will

Henning Schulzrinne Advanced Programming 40

Page 41: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Enumerated typesyp

Just syntactic sugar for ordered collection of integer constants:typedef enum {

Red, Orange, Yellow, g ,} Color;

is like#define Red 0#define Orange 1#define Yellow 2

typedef enum {False, True} boolean;

Henning Schulzrinne Advanced Programming 41

Page 42: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Objects (or lack thereof)j ( ) C does not have objects / classes

but does support abstract data types through separate files declaration (xxx.h) vs. implementation (xxx.c)

Variables for C’s primitive types are defined similarly:Variables for C s primitive types are defined similarly:short int x;char ch;fl t i 3 1415float pi = 3.1415;float f, g;

Variables defined in {} block are active only in block{} y Variables defined outside a block are global (persist

during program execution), but may not be globally visible (static)

Henning Schulzrinne Advanced Programming 42

visible (static)

Page 43: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Data objectsj

Variable = container that can hold a value in C, pretty much a CPU word or similar

default value is (mostly) undefined – treat as random compiler may warn you about uninitialized

variablesvariables ch = ‘a’; x = x + 4;

Always pass by value but can pass address Always pass by value, but can pass address to function:scanf(“%d%f”, &x, &f);

Henning Schulzrinne Advanced Programming 43

Page 44: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Data objectsj Every data object in C has

a name and data type (specified in definition) an address (its relative location in memory) a size (number of bytes of memory it occupies)( y y p ) visibility (which parts of program can refer to it) lifetime (period during which it exists)

Warning: Warning: int *foo(char x) {

return &x;}pt = foo(x);*pt = 17;

Henning Schulzrinne Advanced Programming 44

pt 7;

Page 45: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Data objectsj

Unlike scripting languages and Java, all C data objects have a fixed size over their lifetime

t d i ll t d bj t except dynamically created objects

size of object is determined when object is created:created: global data objects at compile time (data) local data objects at run-time (stack) local data objects at run time (stack) dynamic data objects by programmer (heap)

Henning Schulzrinne Advanced Programming 45

Page 46: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Data object creationjint x;i t [20]int arr[20];void main(int argc, char *argv[]) {

int i = 20;{int x; x = i + 7;}

}void f(int n)( ){

int a, *p;1a = 1;

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

Henning Schulzrinne Advanced Programming 46

Page 47: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Data object creationj malloc() allocates a block of memory Lifetime until memory is freed, with free(). Memory leakage – memory allocated is never

freed:freed:char *combine(char *s, char *t) {u = (char *)malloc(strlen(s) + strlen(t) + 1);if ( ! t) {if (s != t) {strcpy(u, s); strcat(u, t);return u;

} else {} else {return NULL;

}}

Henning Schulzrinne Advanced Programming 47

}

Page 48: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Memory allocationy

Note: malloc() does not initialize data void *calloc(size_t nmemb, size_t size)

does initialize (to zero) malloc(sz) ≈ calloc(sz, 1)

Henning Schulzrinne Advanced Programming 48

Page 49: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Memory layout of programs0

Header info0

100

Code400

Data - Heap

400

560Dynamic memoryall malloc()s

560

1010 Local memory+ function callall normal vars Data - stack

1200 function call

stackall normal vars Data - stack

Page 50: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Data objects and pointersj p The memory address of a data object, e.g., int x

b b d can be obtained via &x has a data type int * (in general, type *) has a value which is a large (4/8 byte) unsigned integerg ( / y ) g g can have pointers to pointers: int **

The size of a data object, e.g., int xb bt i d i i f i f( ) can be obtained via sizeof x or sizeof(x)

has data type size_t, but is often assigned to int (bad!) has a value which is a small(ish) integer is measured in bytes

Henning Schulzrinne Advanced Programming 50

Page 51: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Data objects and pointersj p

Every data type T in C has an associated pointer type T *

A value of type T * is the address of an object of type T

If an object int *xp has value &x, the i * d f th i t dexpression *xp dereferences the pointer and

refers to x, thus has type intxp x

&x 42

xp x

int * int

Henning Schulzrinne Advanced Programming 51

int int

Page 52: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Data objects and pointersj p

If p contains the address of a data object, then *p allows you to use that object

*p is treated just like normal data objectint a, b, *c, *d;*d = 17; /* BAD idea */a = 2; b = 3; c = &a; d = &b;if (*c == *d) puts(“Same value”);*c = 3;if (*c == *d) puts(“Now same value”);if (*c == *d) puts( Now same value );c = d;if (c == d) puts (“Now same address”);

Henning Schulzrinne Advanced Programming 52

Page 53: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

void pointersp

Generic pointervoid *malloc(size_t size);void free(void *ptr);

Unlike other pointers, can be assigned to any other pointer type:

id * ll (13)void *v = malloc(13);char *s = v;

Acts like char * otherwise: Acts like char * otherwise:v++, sizeof(*v) = 1;

Henning Schulzrinne Advanced Programming 53

Page 54: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Structured data objectsj

Structured data objects are available as

object propertyarray [] enumerated,y [] enumerated,

numbered from 0

struct names and types ofstruct names and types of fields

union occupy same spaceunion occupy same space (one of)

Henning Schulzrinne Advanced Programming 54

Page 55: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Arraysy

Arrays are defined by specifying an element type and number of elements int vec[100]; char str[30]; char str[30]; float m[10][10];

Stored as linear arrangement of elementsg For array containing N elements, indexes are

0..N-1 int sum = 0; for (int i = 0; i < N; i++)

sum += vec[i];

Henning Schulzrinne Advanced Programming 55

[ ]

Page 56: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Arraysy C does not remember how large arrays are (i.e., no

length attribute)length attribute) no out-of-bounds checking int x[10]; x[10] = 5; may work (for a while)

In the block where array A is defined: sizeof A gives the number of bytes in array can compute length via sizeof A /sizeof A[0]p g [ ]

When an array is passed as a parameter to a function the size information is not available inside the function array size is typically passed as an additional parameter array size is typically passed as an additional parameter

PrintArray(A, VECSIZE);

or globally #define VECSIZE 10

Henning Schulzrinne Advanced Programming 56

#define VECSIZE 10

Page 57: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Copying arrayspy g y

Copying content vs. copying pointer to contentvoid copy(int A[], int B[], int N){

A = B;}}

Swizzling pointers has no effect, copy contents element-wise insteadvoid copy(int A[], int B[], int N) {

for (int i = 0; i < N; i++) {A[i] = B[i];

}}

Henning Schulzrinne Advanced Programming 57

Page 58: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Strings In Java, strings are regular objects In C, strings are just char arrays with a NUL

g

, g j y(‘\0’) terminator

“a cat” = a c a t \0

A literal string (“a cat”) is automatically allocated memory space to contain it and

the terminating \0the terminating \0 has a value which is the address of the first character can’t be changed by the program (common bug!)

All other strings must have space allocated to them by the program

Henning Schulzrinne Advanced Programming 58

Page 59: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Stringsg We normally refer to a string via a pointer to its first

character:character:char str[] = “my string”;char *s;s = &str[0]; s = str;s = &str[0]; s = str;

C functions only know string ending by \0:char *str = “my string”;

for (int i = 0; str[i] != ‘\0’; i++) putchar(str[i]);

for (char *s = str; *s; s++) putchar(*s);

String library: #include <strings.h> strlen strcpy

Henning Schulzrinne Advanced Programming 59

strlen, strcpy, …

Page 60: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

structs

Similar to fields in Java object/class definitions components can be any type (but not recursive) accessed using the same syntax struct.fieldg y Example:

struct {int x; char y; float z;} rec;...rec.x = 3; rec.y = ‘a’; rec.z= 3.1415;

Henning Schulzrinne Advanced Programming 60

Page 61: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

structs Record types can be defined

using a tag associated with the struct definition wrapping the struct definition inside a typedef

Examples:Examples:struct complex {double real; double imag;};struct point {double x; double y;} corner;typedef struct {double real; double imag;} Complex;typedef struct {double real; double imag;} Complex;struct complex a, b;Complex c,d;

a and b have the same size structure and type a and b have the same size, structure and type a and c have the same size and structure, but

different types

Henning Schulzrinne Advanced Programming 61

yp

Page 62: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Dereferencing pointers to struct elementsstruct elements

Pointers commonly to structsComplex *p;double i;

(*p).real = 42.0;i = (*p).imag;

Note: *p.real doesn’t work Abbreviated alternative:

p->real = 42.0;i = p->imag;

Henning Schulzrinne Advanced Programming 62

Page 63: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

structs

Overall size is sum of elements, plus padding for alignment:struct {

char x;char x;int y;char z;

} s1; sizeof(s1) = ?struct {

char x, z;int y;

} s2; sizeof(s2) = ?

Henning Schulzrinne Advanced Programming 63

Page 64: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

structs

Often used to model real memory layout, e.g.,typedef struct {

u_int16 version:2; /* protocol version */u int16 p:1; /* padding flag */u_ t 6 p: ; / padd g ag /u_int16 x:1; /* header extension flag */u_int16 cc:4; /* CSRC count */

i t16 1 /* k bit */u_int16 m:1; /* marker bit */u_int16 pt:7; /* payload type */u_int16 seq; /* sequence number */u_int32 ts; /* timestamp */u_int32 ssrc; /* synchronization source */

} rtp hdr t;

Henning Schulzrinne Advanced Programming 64

} p_ _ ;

Page 65: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Bit fields

On previous slides, labeled integers with size in bits (e.g., pt:7)

Allows aligning struct with real memory data, e.g., in protocols or device drivers

Order can differ between little/big-endian tsystems

Alignment restrictions on modern processors nat al alignment– natural alignment

Sometimes clearer than (x & 0x8000) >> 31

Henning Schulzrinne Advanced Programming 65

Page 66: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Functions

Prototypes and functions (cf. Java interfaces) extern int putchar(int c); putchar(‘A’); int putchar(int c) {t putc a ( t c) {

do something interesting here}

f f f f f If defined before use in same file, no need for prototypeT i ll t t d fi d i h fil Typically, prototype defined in .h file

Good idea to include <.h> in actual definition

Henning Schulzrinne Advanced Programming 66

Page 67: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Functions

static functions and variables hide them to those outside the same file:static int x;static int times2(int c) {static int times2(int c) {

return c*2;}

compare protected class members in Java.

Advanced Programming 67Henning Schulzrinne

Page 68: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Program with multiple filesProgram w th mult ple f les#include <stdio.h> void myproc(void);#include “mypgm.h”

void main(void){

mypgm.h

{myproc();

}

#include “mypgm.h”

static int mydata;

main.c void myproc(void){

d t 2 Library headers

StandardU d fi d

mydata=2;. . . /* some code */

}

Henning Schulzrinne Advanced Programming 68

User-defined mypgm.c

Page 69: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Data hiding in Cg C doesn’t have classes or private members, but this can be

approximatedapproximated Implementation defines real data structure:

#include “queue.h” // good practicetypedef struct queue_t {struct queue_t *next;int data;

} *queue_t;

queue_t NewQueue(void) {return calloc(1, sizeof(struct queue_t)); // with 0 contents

}

H d fil d fi bli d Header file defines public data:typedef struct queue_t *queue_t;queue_t NewQueue(void);

Henning Schulzrinne Advanced Programming 69

Page 70: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Function pointersp functions can be used as values (i.e. passed by reference)

int foo(); // function returning integerint *bar(); // function returning pointer to intint (*fp)(); // pointer to function returning intint *(*fpp)();// pointer to func returning ptr to int

fp = foo;fpp = bar;

int i = fp();int j = *(fpp());

Henning Schulzrinne Advanced Programming 70

Page 71: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Function pointersp to install interrupt handlers (timers, etc)

#include <signal.h>

typedef void (*sighandler_t)(int);

sighandler_t signal(int signum, sighandler_t handler);

to register call back functions to implement polymorphismto implement polymorphism

Henning Schulzrinne Advanced Programming 71

Page 72: Embedded Software · Better control of low-level mechanisms memory allocation, specific memory locations Ideal for ... concurrency (threads) library functions Henning Schulzrinne

Before you goBefore you go…. Always initialize anything before using it (especially

pointers)pointers) Don’t use pointers after freeing them Don’t return a function’s local variables by referenceDon t return a function s local variables by reference No exceptions – so check for errors everywhere

memory allocation system calls Murphy’s law, C version: anything that can’t fail, will fail

An array is also a pointer but its value is immutableAn array is also a pointer, but its value is immutable.

Henning Schulzrinne Advanced Programming 72