Not Your Fathers C
C Application Development In 2016
Introduction
About Me
● Living in Leipzig
● five years of exploring ways to write high
level C
● C and me is a „convenience marriage“
(Zweck Ehe)
● Other tech stuff: Python, Java
● http://blog.toepfer.nu
Introduction
Leipzig Softwerkskammer
● Software Craftsmanship Community in
Leipzig
● Once a month
● Mix of coding and beer
● https://www.softwerkskammer.org/groups/
sachsen
Introduction
My C Scope
● Application development in a legacy
system
● No embedded software
● I am not a kernel hacker
Introduction
Why Still C
● Legacy Code
● Embedded systems
● Speed
● Direct Memory Control (Garbage Collection
can be slow!)
A Punk Rock Language
[1]
A Punk Rock Language
Essay in PragProg Magazine
March 2011
[2]
A Punk Rock Language
1978
● Book release and first peak of Punk Rock
[4][3]
A Punk Rock Language
Three Chords Is Enough To
Form A Band
[5]
A Punk Rock Language
Three Basic Data Types In C
[6]
A Punk Rock Language
The Craftsman's Question
C is quirky, flawed, and an enormous
success.. (Dennis Ritchie On C)
[7]
How To Deal
With A Punk Rock
Language?
Structure
Structure
“On Information Hiding”
● „On the criteria to be used in decomposing
systems into modules”, CACM, Dec., 1972
by David L. Parnas.
● Bottom line: Modularization is a very old
concept
Structure
A C Module
● A *.c file is called a “module”
● Should contain related functions and data
● How to design related functions and data –
can't we have classes?
Structure
What Is A Class
● A bunch of functions working on (mainly)
the same variables. (Uncle Bob)
● That's exactly what we have – how to
implement this in C?
Structure
Main OO Structure Elements
● Classes – defines an object
● Methods – actions on the object's data
● Packages – organizing classes
Structure
A Python Example
from long.package.path.my_class import MyClass
...
my_instance = MyClass()
print(my_instance.say_hello())
Structure
Objects in C
● Only function names in global name space
● We need to use a naming convention for
structuring:
– Class name
– Underscore
– Method name
Structure
Naming Example
● The Module name: MyClass.c
● Functions inside:
– The constructor: MyClass_create()
– A method: MyClass_sayHello()
– The destructor: MyClass_destroy()
Structure
Example Ported To C
#include "MyClass.h"
...
MyClass *my_instance = MyClass_create();
printf("%sn", MyClass_sayHello(my_instance));
MyClass_destroy(my_instance);
Structure
Objects in C
● C can give you Object Orientation –
Without Inheritance
● It's no real OO – I just call it „Objects in C“
● Not to be mistaken with *.o files which are
compiler result files
Structure
Objects In C - My Rules
● treat a C module as a class
● all public functions of that file are the methods of
the class
● the first part of the function name is the name of
the class
● the second part of the function name is the name
of the method
● The first argument of the function is the instance
of the object
Structure
No Hard Rules
● A module can be designed as an object – but
it doesn't have to – simply related functions
are still ok.
● I prefer camel case for class and method
names but there are other ways as well (see
next example).
● As with every convention:
– define your rules and stick to it
– it's not a religion
Structure
Pebble Smart Watch
● Smart watch which started as crowd
funding campaign
[8]
Structure
„Hello Pebble“
Window *window;
TextLayer *text_layer;
void init() {
window = window_create();
text_layer = text_layer_create(GRect(0, 0, 144, 40));
text_layer_set_text(text_layer, "Hello, Pebble!");
layer_add_child(window_get_root_layer(window),
text_layer_get_layer(text_layer));
window_stack_push(window, true);
}
void deinit() {
text_layer_destroy(text_layer);
window_destroy(window);
}
int main() {
init();
app_event_loop();
deinit();
return 0;
}
Abstraction
Abstraction
An Old Idea
Taken from „The Structure And Interpretation Of
Computer Programs“, 2nd Edition, MIT Press, 1996
Abstraction
The Standards
● ANSI standard (Strings, Math, Memory)
● Is enhanced by the Posix Standard
(Sockets, File descriptors...)
● Covers the bare minimum
● “1000” string functions and non is the right
one
Abstraction
What I Expect
● Lists
● Hashtable/ Associative Array/ Dictionary
● Painless Strings
● …
● Basically: Not Re-Inventing The Wheel
Every Time
Abstraction
GLib2
● https://developer.gnome.org/glib/
● Initially developed by GNOME but
separated GTK+ to be used in other
software
● Not to be mistaken with glibc (GNU
Implementation of the ANSI and Posix
Standards)
Abstraction
GLib2
● „the missing standard library“
● „Boost for C“
● In my opinion the best universal purpose
library for C – but there are others as well
(Apache)
Abstraction
GLib2 List Example
GList *beers = NULL;
beers = g_list_append(beers, g_strdup("Helles"));
beers = g_list_append(beers, g_strdup("Pils"));
beers = g_list_append(beers, g_strdup("Weizen"));
printf("I know %i beers.n", g_list_length(beers));
printf("The third beer is a %s.n",
(char*)g_list_nth_data(beers, 2));
GList *iterator = beers;
puts("All beers:");
while (iterator != NULL) {
printf("%sn", (char*)iterator->data);
iterator = g_list_next(iterator);
}
g_list_free_full(beers, free);
Error Handling
Error Handling
Back To The Basics
● No fancy stuff like try / catch blocks and
exceptions
● Has to be done manually
● There is a third state: undefined
Error Handling
Classic Via Return Code
int doCalculations()
{
    int rc = calcSomething();
 
    if (rc != OK)
    {
        printf("function calcSomething had an error.n");
        return NOT_OK;
    }
 
    rc = calcSomethingElse();
 
    if (rc != OK)
    {
        printf("function calcSomethingElse had an error.n");
        return NOT_OK;
    }
 
    return OK;
}
Error Handling
A Case For goto
int doCalculations()
{
int rc = calcSomething();
if (rc != OK) goto error_calcSomething;
rc = calcSomethingElse();
if (rc != OK) goto error_calcSomethingElse;
return OK;
// error handling
error_calcSomething:
printf("function calcSomething had an error.n");
return NOT_OK;
error_calcSomethingElse:
printf("function calcSomethingElse had an error.n");
return NOT_OK;
}
Error Handling
A Case For goto
● Only use it for local error handling & clean
up
● The rule: “Jump forward in a function”
● No replacement for „continue“ and „break“
in loops
Error Handling
An empirical study of goto in C code
● University study published in 2015 *
● Analysis of all C code at github.com
– 2 million lines of Code
– 11 000 repositories
● Result
– 80 % use goto for error handling
– 40% use it for resource clean up
* https://peerj.com/preprints/826v1/
Error Handling
Conclusion of the Study
We conclude that developers limit
themselves to using goto appropriately in
most cases, and not in an unrestricted
manner like Dijkstra feared, thus
suggesting that goto does not appear to be
harmful in practice.
Testing
Testing
Unit Testing Is Universal
● “self testing code” is of course possible in
C as well
● Requires good understanding of the code >
compile > link > execute cycle
● many unit testing frameworks are available,
popular are:
– CppuTest
– googletest
Testing
A Futter Machine
Testing
The Big Picture
Testing
Test First
Testing
No Such Function
machine_test.c:9:5: warning: implicit declaration of function
‘Machine_create’ [-Wimplicit-function-declaration]
rc = Machine_create();
^
/tmp/ccThL6ze.o: In function `create_ok':
machine_test.c:(.text+0x15): undefined reference to `Machine_create'
collect2: error: ld returned 1 exit status
● one warning and one error:
– Compiler: Unknown function, auto-detecting prototype
missing
– Linker: Implementation missing
Testing
Provide The Interface
Testing
Implementation Still Missing
/tmp/ccOl0iLr.o: In function
`test_create_machine_with_no_error':
machine_test.c:(.text+0x15): undefined reference to
`Machine_create'
collect2: error: ld returned 1 exit status
● linker still complaining about missing
implementation
Testing
Provide A Simple Implementation
Testing
The Test Passes
● Now everything required is present:
– Test (our mini application)
– Interface (the header file)
– Implementation (the machine.c file)
Testing
The Big Picture Revisted
Old Friends
Old Friends
Function Pointer
● Define the code to be executed at runtime
● “Typed functional programming”
● “registering a callback” – that’s a function
pointer
● Awkward syntax but very useful
Old Friends
Function Pointer Example
// calc functions
int addInt(int a, int b) {return a + b;}
int multiplyInt(int a, int b) {return a * b;}
int calcInt(int a, int b, int (*calcFunction)(int,int)) {
return calcFunction(a, b);
}
int main(void) {
int sum = calcInt(2, 3, addInt);
int product = calcInt(2, 3, multiplyInt);
printf("Sum is %i, product is %in", sum, product);
}
Old Friends
Language Bridges
● Integrate C code in other programming
language
● Develop “high level” and fall back when
– Using existing C library
– CPU cycles matter
– …
● More likely at application edges than core
Old Friends
Bridging from Python To C (ctypes)
int add(int a, int b) {
return a + b;
}
C function in libmaikmath.so:
import ctypes
mylib = ctypes.cdll.LoadLibrary('libmaikmath.so')
print('1 + 2 =', mylib.add(1, 2))
Using “add” in a Python program:
Warning: Oversimplified
How To Code
How To Code
My Conventions
● Code for the programmer after me - not the
machine
● Rarely use Macros - adds one more
indirection in my head
● Try to keep it plain C pimped with modern
libraries - but not a new language
(GObject/ GTK, libcello)
How To Code
I Like IDEs
● My setup:
– Eclipse CDT with
– VIM plugin and
– Running on Linux in a Vagrant provided Virtualbox
– Windows 7 Host
● JetBrains CLion looks promising
● My next try: Visual Studio Code
with C/ C++ plugin
How To Code
Eclipse CDT Example
Further Reading
Further Reading
Getting Started
[9]
Further Reading
Structure
[10]
Further Reading
Syntax
[11]
Further Reading
Online
● Nice Primer:
http://developer.getpebble.com/tutorials/be
ginner/primer
● How To C in 2016 – good discussion:
https://matt.sh/howto-c
● My collection of C tips:
http://we-press-buttons.blogspot.de/search/
label/C
Thank You For Your Attention
[12]
Image References
● [1] - http://www.bilbaoisrock.com/wp-content/uploads/2013/04/the-ramones.jpg
● [2] - https://pragprog.com/magazines/2011-03/punk-rock-languages
● [3] -
https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/The_C_Programming_Language,_First_Edition_Cover_
(2).svg/2000px-
The_C_Programming_Language,_First_Edition_Cover_(2).svg.png
● [4] - https://ryebreadrodeo.com/prodimages/cz117.jpg
● [5] - http://blog.sharemyguitar.com/wp-content/uploads/2012/03/SMG-Power-Chord.jpg
● [6] - http://codingfox.com/wp-content/uploads/2013/08/data-types.gif
● [7] - https://upload.wikimedia.org/wikipedia/commons/2/26/Card_reader_segfault.jpg
● [8] - http://cdn.mos.techradar.com/art/Watches/Pebble/Pebble%202/Time_2_Collection-970-80.jpg
● [9] - http://ecx.images-amazon.com/images/I/41%2BbFKtFHjL._SX405_BO1,204,203,200_.jpg
● [10] - https://imagery.pragprog.com/products/173/jgade.jpg?1298589886
● [11] - http://ecx.images-amazon.com/images/I/51Rs4gK05iL._SX379_BO1,204,203,200_.jpg
● [12] - http://agilebacon.com/wp-content/uploads/2014/07/exhausted-student-with-laptop.jpg
Backup
Abstraction
String Copy Tour
● Scenario
– Copy a string to a new string
– The memory for the new string is smaller than
the original one
Abstraction
Strings In C
● NUL (‘0’) terminated array of single bytes
● Example:
char source[] = "abcde";
a b c d e ?? 0
Abstraction
String Copy with strcpy
● First appeared 1975
● Bells/ AT&T: Programmer's Workbench
(PWB/UNIX)
● Renowned for Buffer Overflows
Abstraction
strcpy Example
char source[] = "abcde";
char destination[4] = {0};
0 0 0 0 ?? ????
Content of “destination”:
strcpy(destination, source);
Buffer Overflow
a b c d ?? ??0e
Content of “destination”:
Abstraction
String Copy with strncpy
● First appeared 1979
● AT&T Unix Version 7
● Found wider usage in the 1990ies to
overcome strcpy problems
● Problem: Does not guarantee a proper C
string as result.
Abstraction
strncpy Example
char source[] = "abcde";
char destination[4] = {0};
0 0 0 0 ?? ????
Content of “destination”:
strncpy(destination, source,
sizeof(destination));
No NUL
byte
??a b c d? ???
Content of “destination”:
Next usage of “destination” will read
these bytes until NUL is found.
Abstraction
String Copy with strlcpy
● First appeared 1998 (OpenBSD)
● Aim:
– No buffer overflows
– Produce always valid C Strings (NUL terminated)
● Problems:
– Truncates strings (controversial)
– No adoption into standards
– Third party libs required
Abstraction
strlcpy Example
char source[] = "abcde";
char destination[4] = {0};
0 0 0 0 ?? ????
Content of “destination”:
strlcpy(destination, source,
sizeof(destination));
String content is incomplete
??a b c 0? ???
Content of “destination”:
Abstraction
String Copy with strcpy_s
● First appeared 2003 (Microsoft)
● Solves the previous problems
● Is part of C11 standard (optional appendix)
● Currently only available as third party
library
– “Safe C” by Cisco
– https://sourceforge.net/projects/safeclib/
Abstraction
strcpy_s Example
char source[] = "abcde";
char destination[4] = {0};
0 0 0 0 ?? ????
Content of “destination”:
??0 0 0 0? ???
Content of “destination”:
errno_t result = strcpy_s(destination,
sizeof(destination), source);ESLEMAX (length exceeds max)
Abstraction
Alternative String Copy Approaches
● Heap based
● Memory allocation automatically
● Must be freed manually
● Must be checked if successful
Abstraction
Alternative String Copy Approaches
● asprintf
– GNU extension of C standard
– Part of glibc
● GLib Strings
– Part of Glib
– Object like behaviour
– Offers functions like “append”, “up”, “down”…
● ...
Not Your Fathers C - C Application Development In 2016

Not Your Fathers C - C Application Development In 2016

  • 1.
    Not Your FathersC C Application Development In 2016
  • 2.
    Introduction About Me ● Livingin Leipzig ● five years of exploring ways to write high level C ● C and me is a „convenience marriage“ (Zweck Ehe) ● Other tech stuff: Python, Java ● http://blog.toepfer.nu
  • 3.
    Introduction Leipzig Softwerkskammer ● SoftwareCraftsmanship Community in Leipzig ● Once a month ● Mix of coding and beer ● https://www.softwerkskammer.org/groups/ sachsen
  • 4.
    Introduction My C Scope ●Application development in a legacy system ● No embedded software ● I am not a kernel hacker
  • 5.
    Introduction Why Still C ●Legacy Code ● Embedded systems ● Speed ● Direct Memory Control (Garbage Collection can be slow!)
  • 6.
    A Punk RockLanguage [1]
  • 7.
    A Punk RockLanguage Essay in PragProg Magazine March 2011 [2]
  • 8.
    A Punk RockLanguage 1978 ● Book release and first peak of Punk Rock [4][3]
  • 9.
    A Punk RockLanguage Three Chords Is Enough To Form A Band [5]
  • 10.
    A Punk RockLanguage Three Basic Data Types In C [6]
  • 11.
    A Punk RockLanguage The Craftsman's Question C is quirky, flawed, and an enormous success.. (Dennis Ritchie On C) [7] How To Deal With A Punk Rock Language?
  • 12.
  • 13.
    Structure “On Information Hiding” ●„On the criteria to be used in decomposing systems into modules”, CACM, Dec., 1972 by David L. Parnas. ● Bottom line: Modularization is a very old concept
  • 14.
    Structure A C Module ●A *.c file is called a “module” ● Should contain related functions and data ● How to design related functions and data – can't we have classes?
  • 15.
    Structure What Is AClass ● A bunch of functions working on (mainly) the same variables. (Uncle Bob) ● That's exactly what we have – how to implement this in C?
  • 16.
    Structure Main OO StructureElements ● Classes – defines an object ● Methods – actions on the object's data ● Packages – organizing classes
  • 17.
    Structure A Python Example fromlong.package.path.my_class import MyClass ... my_instance = MyClass() print(my_instance.say_hello())
  • 18.
    Structure Objects in C ●Only function names in global name space ● We need to use a naming convention for structuring: – Class name – Underscore – Method name
  • 19.
    Structure Naming Example ● TheModule name: MyClass.c ● Functions inside: – The constructor: MyClass_create() – A method: MyClass_sayHello() – The destructor: MyClass_destroy()
  • 20.
    Structure Example Ported ToC #include "MyClass.h" ... MyClass *my_instance = MyClass_create(); printf("%sn", MyClass_sayHello(my_instance)); MyClass_destroy(my_instance);
  • 21.
    Structure Objects in C ●C can give you Object Orientation – Without Inheritance ● It's no real OO – I just call it „Objects in C“ ● Not to be mistaken with *.o files which are compiler result files
  • 22.
    Structure Objects In C- My Rules ● treat a C module as a class ● all public functions of that file are the methods of the class ● the first part of the function name is the name of the class ● the second part of the function name is the name of the method ● The first argument of the function is the instance of the object
  • 23.
    Structure No Hard Rules ●A module can be designed as an object – but it doesn't have to – simply related functions are still ok. ● I prefer camel case for class and method names but there are other ways as well (see next example). ● As with every convention: – define your rules and stick to it – it's not a religion
  • 24.
    Structure Pebble Smart Watch ●Smart watch which started as crowd funding campaign [8]
  • 25.
    Structure „Hello Pebble“ Window *window; TextLayer*text_layer; void init() { window = window_create(); text_layer = text_layer_create(GRect(0, 0, 144, 40)); text_layer_set_text(text_layer, "Hello, Pebble!"); layer_add_child(window_get_root_layer(window), text_layer_get_layer(text_layer)); window_stack_push(window, true); } void deinit() { text_layer_destroy(text_layer); window_destroy(window); } int main() { init(); app_event_loop(); deinit(); return 0; }
  • 26.
  • 27.
    Abstraction An Old Idea Takenfrom „The Structure And Interpretation Of Computer Programs“, 2nd Edition, MIT Press, 1996
  • 28.
    Abstraction The Standards ● ANSIstandard (Strings, Math, Memory) ● Is enhanced by the Posix Standard (Sockets, File descriptors...) ● Covers the bare minimum ● “1000” string functions and non is the right one
  • 29.
    Abstraction What I Expect ●Lists ● Hashtable/ Associative Array/ Dictionary ● Painless Strings ● … ● Basically: Not Re-Inventing The Wheel Every Time
  • 30.
    Abstraction GLib2 ● https://developer.gnome.org/glib/ ● Initiallydeveloped by GNOME but separated GTK+ to be used in other software ● Not to be mistaken with glibc (GNU Implementation of the ANSI and Posix Standards)
  • 31.
    Abstraction GLib2 ● „the missingstandard library“ ● „Boost for C“ ● In my opinion the best universal purpose library for C – but there are others as well (Apache)
  • 32.
    Abstraction GLib2 List Example GList*beers = NULL; beers = g_list_append(beers, g_strdup("Helles")); beers = g_list_append(beers, g_strdup("Pils")); beers = g_list_append(beers, g_strdup("Weizen")); printf("I know %i beers.n", g_list_length(beers)); printf("The third beer is a %s.n", (char*)g_list_nth_data(beers, 2)); GList *iterator = beers; puts("All beers:"); while (iterator != NULL) { printf("%sn", (char*)iterator->data); iterator = g_list_next(iterator); } g_list_free_full(beers, free);
  • 33.
  • 34.
    Error Handling Back ToThe Basics ● No fancy stuff like try / catch blocks and exceptions ● Has to be done manually ● There is a third state: undefined
  • 35.
    Error Handling Classic ViaReturn Code int doCalculations() {     int rc = calcSomething();       if (rc != OK)     {         printf("function calcSomething had an error.n");         return NOT_OK;     }       rc = calcSomethingElse();       if (rc != OK)     {         printf("function calcSomethingElse had an error.n");         return NOT_OK;     }       return OK; }
  • 36.
    Error Handling A CaseFor goto int doCalculations() { int rc = calcSomething(); if (rc != OK) goto error_calcSomething; rc = calcSomethingElse(); if (rc != OK) goto error_calcSomethingElse; return OK; // error handling error_calcSomething: printf("function calcSomething had an error.n"); return NOT_OK; error_calcSomethingElse: printf("function calcSomethingElse had an error.n"); return NOT_OK; }
  • 37.
    Error Handling A CaseFor goto ● Only use it for local error handling & clean up ● The rule: “Jump forward in a function” ● No replacement for „continue“ and „break“ in loops
  • 38.
    Error Handling An empiricalstudy of goto in C code ● University study published in 2015 * ● Analysis of all C code at github.com – 2 million lines of Code – 11 000 repositories ● Result – 80 % use goto for error handling – 40% use it for resource clean up * https://peerj.com/preprints/826v1/
  • 39.
    Error Handling Conclusion ofthe Study We conclude that developers limit themselves to using goto appropriately in most cases, and not in an unrestricted manner like Dijkstra feared, thus suggesting that goto does not appear to be harmful in practice.
  • 40.
  • 41.
    Testing Unit Testing IsUniversal ● “self testing code” is of course possible in C as well ● Requires good understanding of the code > compile > link > execute cycle ● many unit testing frameworks are available, popular are: – CppuTest – googletest
  • 42.
  • 43.
  • 44.
  • 45.
    Testing No Such Function machine_test.c:9:5:warning: implicit declaration of function ‘Machine_create’ [-Wimplicit-function-declaration] rc = Machine_create(); ^ /tmp/ccThL6ze.o: In function `create_ok': machine_test.c:(.text+0x15): undefined reference to `Machine_create' collect2: error: ld returned 1 exit status ● one warning and one error: – Compiler: Unknown function, auto-detecting prototype missing – Linker: Implementation missing
  • 46.
  • 47.
    Testing Implementation Still Missing /tmp/ccOl0iLr.o:In function `test_create_machine_with_no_error': machine_test.c:(.text+0x15): undefined reference to `Machine_create' collect2: error: ld returned 1 exit status ● linker still complaining about missing implementation
  • 48.
  • 49.
    Testing The Test Passes ●Now everything required is present: – Test (our mini application) – Interface (the header file) – Implementation (the machine.c file)
  • 50.
  • 51.
  • 52.
    Old Friends Function Pointer ●Define the code to be executed at runtime ● “Typed functional programming” ● “registering a callback” – that’s a function pointer ● Awkward syntax but very useful
  • 53.
    Old Friends Function PointerExample // calc functions int addInt(int a, int b) {return a + b;} int multiplyInt(int a, int b) {return a * b;} int calcInt(int a, int b, int (*calcFunction)(int,int)) { return calcFunction(a, b); } int main(void) { int sum = calcInt(2, 3, addInt); int product = calcInt(2, 3, multiplyInt); printf("Sum is %i, product is %in", sum, product); }
  • 54.
    Old Friends Language Bridges ●Integrate C code in other programming language ● Develop “high level” and fall back when – Using existing C library – CPU cycles matter – … ● More likely at application edges than core
  • 55.
    Old Friends Bridging fromPython To C (ctypes) int add(int a, int b) { return a + b; } C function in libmaikmath.so: import ctypes mylib = ctypes.cdll.LoadLibrary('libmaikmath.so') print('1 + 2 =', mylib.add(1, 2)) Using “add” in a Python program: Warning: Oversimplified
  • 56.
  • 57.
    How To Code MyConventions ● Code for the programmer after me - not the machine ● Rarely use Macros - adds one more indirection in my head ● Try to keep it plain C pimped with modern libraries - but not a new language (GObject/ GTK, libcello)
  • 58.
    How To Code ILike IDEs ● My setup: – Eclipse CDT with – VIM plugin and – Running on Linux in a Vagrant provided Virtualbox – Windows 7 Host ● JetBrains CLion looks promising ● My next try: Visual Studio Code with C/ C++ plugin
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
    Further Reading Online ● NicePrimer: http://developer.getpebble.com/tutorials/be ginner/primer ● How To C in 2016 – good discussion: https://matt.sh/howto-c ● My collection of C tips: http://we-press-buttons.blogspot.de/search/ label/C
  • 65.
    Thank You ForYour Attention [12]
  • 66.
    Image References ● [1]- http://www.bilbaoisrock.com/wp-content/uploads/2013/04/the-ramones.jpg ● [2] - https://pragprog.com/magazines/2011-03/punk-rock-languages ● [3] - https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/The_C_Programming_Language,_First_Edition_Cover_ (2).svg/2000px- The_C_Programming_Language,_First_Edition_Cover_(2).svg.png ● [4] - https://ryebreadrodeo.com/prodimages/cz117.jpg ● [5] - http://blog.sharemyguitar.com/wp-content/uploads/2012/03/SMG-Power-Chord.jpg ● [6] - http://codingfox.com/wp-content/uploads/2013/08/data-types.gif ● [7] - https://upload.wikimedia.org/wikipedia/commons/2/26/Card_reader_segfault.jpg ● [8] - http://cdn.mos.techradar.com/art/Watches/Pebble/Pebble%202/Time_2_Collection-970-80.jpg ● [9] - http://ecx.images-amazon.com/images/I/41%2BbFKtFHjL._SX405_BO1,204,203,200_.jpg ● [10] - https://imagery.pragprog.com/products/173/jgade.jpg?1298589886 ● [11] - http://ecx.images-amazon.com/images/I/51Rs4gK05iL._SX379_BO1,204,203,200_.jpg ● [12] - http://agilebacon.com/wp-content/uploads/2014/07/exhausted-student-with-laptop.jpg
  • 67.
  • 68.
    Abstraction String Copy Tour ●Scenario – Copy a string to a new string – The memory for the new string is smaller than the original one
  • 69.
    Abstraction Strings In C ●NUL (‘0’) terminated array of single bytes ● Example: char source[] = "abcde"; a b c d e ?? 0
  • 70.
    Abstraction String Copy withstrcpy ● First appeared 1975 ● Bells/ AT&T: Programmer's Workbench (PWB/UNIX) ● Renowned for Buffer Overflows
  • 71.
    Abstraction strcpy Example char source[]= "abcde"; char destination[4] = {0}; 0 0 0 0 ?? ???? Content of “destination”: strcpy(destination, source); Buffer Overflow a b c d ?? ??0e Content of “destination”:
  • 72.
    Abstraction String Copy withstrncpy ● First appeared 1979 ● AT&T Unix Version 7 ● Found wider usage in the 1990ies to overcome strcpy problems ● Problem: Does not guarantee a proper C string as result.
  • 73.
    Abstraction strncpy Example char source[]= "abcde"; char destination[4] = {0}; 0 0 0 0 ?? ???? Content of “destination”: strncpy(destination, source, sizeof(destination)); No NUL byte ??a b c d? ??? Content of “destination”: Next usage of “destination” will read these bytes until NUL is found.
  • 74.
    Abstraction String Copy withstrlcpy ● First appeared 1998 (OpenBSD) ● Aim: – No buffer overflows – Produce always valid C Strings (NUL terminated) ● Problems: – Truncates strings (controversial) – No adoption into standards – Third party libs required
  • 75.
    Abstraction strlcpy Example char source[]= "abcde"; char destination[4] = {0}; 0 0 0 0 ?? ???? Content of “destination”: strlcpy(destination, source, sizeof(destination)); String content is incomplete ??a b c 0? ??? Content of “destination”:
  • 76.
    Abstraction String Copy withstrcpy_s ● First appeared 2003 (Microsoft) ● Solves the previous problems ● Is part of C11 standard (optional appendix) ● Currently only available as third party library – “Safe C” by Cisco – https://sourceforge.net/projects/safeclib/
  • 77.
    Abstraction strcpy_s Example char source[]= "abcde"; char destination[4] = {0}; 0 0 0 0 ?? ???? Content of “destination”: ??0 0 0 0? ??? Content of “destination”: errno_t result = strcpy_s(destination, sizeof(destination), source);ESLEMAX (length exceeds max)
  • 78.
    Abstraction Alternative String CopyApproaches ● Heap based ● Memory allocation automatically ● Must be freed manually ● Must be checked if successful
  • 79.
    Abstraction Alternative String CopyApproaches ● asprintf – GNU extension of C standard – Part of glibc ● GLib Strings – Part of Glib – Object like behaviour – Offers functions like “append”, “up”, “down”… ● ...

Editor's Notes

  • #11 Quirky – skuril, sonderbar
  • #27 - Zahlen, die sich durch Brüche ganzer Zahlen ausdrücken lassen. - cons cell – two elements - car -extracts first, cdr extracts second - numerator – Zähler - denominator - Nenner