SlideShare une entreprise Scribd logo
Systèmes
d'exploitation
Le Langage C
Allocation de mémoire
Pirates of Silicon Valley
2
Hidden Figures
3
Dennis Ritchie
• Américain
• Harvard University
• Auteur de langage C
• Co-auteur UNIX
4
Contenu
• Le langage C
• Le standard POSIX
• Allocation de mémoire
5
Bibliographie pour aujourd'hui
• Dan Gookin, C for Dummies (2nd Edition)
– Chapitre 6, 24, 27 et 29
• Peter D. Hipson, Advanced C
– Chapitre 2, 3, 7, 14 et 15
• Steve Summit, C Programming Notes
– Chapitre 6, 8, 9, 10 et 11
6
LANGAGE C
7
Langage C
• Ecrit par Denis Ritchie, 1972
• Bell Labs
• A été écrit pour UNIX
• Portable
– Fonction sur presque toutes SE
• Macro Assembleur
• Fichiers .h et .c
• Diffèrent de C++
8
Standards C
• Original – K&R C
• Plus utilisé ANSI C (C89 ou C90)
• Plus stricte C99
– Plus de types des données
• Plus nouveau C11 et C18
• Embedded C
9
Bibliothèque C
• Libc
– fonctions qui sont disponible dans toutes les SE
• Pour un nouveau SE, c’est la premier
bibliothèque implémenté
• Exemple
– printf / scanf
– malloc / free
– fopen / fread
10
Compilateurs pour le langage C
• GNU Compiler Collection (gcc)
• Low Level Virtual Machine (llvm - clang)
• Microsoft Visual C++ (msvc)
• Intel C
11
La structure d’un program en C
// defines
#define VALUE 10000
...
// variables declaration
int main ()
{
// variables declaration
// statements (code)
return 0;
}
int f ()
{
// variables declaration
// statements (code)
}
12
POSIX
13
POSIX
• Standard
• Portable Operating System Interface
• POSIX – 1
– comprend ANSI C
• POSIX – 1b – Temps Réel
• POSIX – 1c - Fils d’exécutions
• POSIX -2 – Shell et outilles
14
SE conformes avec POSIX
15
MACRO
16
Macro Definition
#define SIZE 1000;
long vector[SIZE];
17
Macro après la Compilation
long vector[1000;];
18
Erreur
Macro Definition
#define SIZE 1000
long vector[SIZE];
19
Macro après la Compilation
long vector[1000];
20
Utilisation des Macros
• Utilisé pour définition de constants
• Paramétriez le programme
• Modifier les valeurs en un seul endroit
21
ALLOCATION DE MEMOIRE
22
Disposition de la mémoire
23
Pointeurs
24
La memoire en C
• Pointeurs
– nom, adresse, adresse référencée
• Valeur
– adresse de mémoire (numéro)
– NULL (numéro 0)
• Fonctions
– sizeof
– malloc
– calloc
– realloc
– free
25
Valeur NULL
• Valeur 0
#define NULL ((void*)0)
• Protection
– La adresse 0 n’est pas utilise
26
sizeof
operateur sizeof (data)
data – variable ou type de données
Renvoie le nombre d'octets occupés par data
27
sizeof
• sizeof (short) ?
– 2
• sizeof (char) ?
– 1
• sizeof (long) ?
– 4
• sizeof (int) ?
– 4 ou 8
• sizeof (long long) ?
– 8
• int f; sizeof (f) ?
– 4 ou 8
28
malloc
void *malloc (size_t size);
size - nombre de octets demandée
renvoie:
• Succès: pointeur vers la mémoriel allouée
• Erreur: NULL
La mémoire alloue n’a pas toujours la valeur 0
int *s = (int*)malloc (sizeof (int))
pourquoi pas sizeof (4)?
29
calloc
void *calloc (size_t count, size_t size);
count – nombre d'objets à allouer
size – taille en octets d'objets à allouer
renvoie:
• Succès: pointeur vers la mémoriel allouée
• Erreur: NULL
La mémoire alloue este avec la valeur 0
// one item
int *s = (int*)calloc (1, sizeof (int));
// array of items
int *v = (int*)calloc (100, sizeof (int));
30
realloc
void *realloc (void *ptr, size_t size);
ptr - pointeur précédemment alloue
size - nombre nouveau de octets demandée
renvoie:
• Succès: pointeur vers la nouveau mémoriel allouée
• Erreur: NULL
La mémoire nouveau alloue n’a pas toujours la valeur 0
// resize the s array
s = (int*)realloc (s, 100*sizeof(int));
31
free
void free (void *ptr);
ptr - pointeur à libérer
free (s); // s does not become
NULL
s = NULL; // important
ptr ne change pas sa valeur en NULL
32
Fuite de mémoire
Il n'y a aucun moyen de libérer un pointeur
int *p = (int*)malloc (sizeof(int));
…
p = NULL; // p is leaked
33
Valgrind
valgrind.org
malloc – vérifiez le retour
int *s = (int*) malloc (sizeof (int))
if (s != NULL)
{
…
}
else
{
perror ("malloc");
abort ();
}
34
Déréférencer un pointeur
int a = 510;
int *p = NULL;
p = &a; // &a - address of variable a
printf ("%dn", a); // prints 510
printf ("%dn", p); // prints the address
of a
printf ("%dn", *p); // prints 510 (the
value at the address of a)
35
Déréférencer un pointeur
int *a = NULL;
a = (int*)malloc (sizeof(int));
if (a != NULL)
{
*a = 510;
printf ("%dn", a); // prints ...?
printf ("%dn", *a); // prints ...?
free (a);
a = NULL;
}
else
{
perror ("malloc");
abort ();
}
36
Déréférencer un pointeur
int *a = NULL;
a = (int*)malloc (sizeof(int));
if (a != NULL)
{
*a = 510;
printf ("%dn", a); // prints the address of a
printf ("%dn", *a); // prints 510
free (a);
a = NULL;
}
else
{
perror ("malloc");
abort ();
}
37
STRINGS
38
String - C Style
s t r i n g 0 …
115 116 114 105 110 103 0 …
char s[N] N
39
Déclaration pour string
char s[100];
// use s
char *s = NULL;
s = (char*)malloc ( ... ? );
// use s
free (s);
s = NULL;
40
Déclaration pour string
char s[100];
// use s
char *s = NULL;
s = (char*)malloc (100*sizeof(char));
// use s
free (s);
s = NULL;
41
Déclaration pour string
char s[100];
// use s
char *s = NULL;
s = (char*)calloc (100, sizeof(char));
// use s
free (s);
s = NULL;
42
Allouer un string
text <- "SE subject"
char *text = NULL;
text = (char*) malloc (…)
strncpy (text, "SE subject", ...);
43
Allouer un string
text <- "SE subject"
char *text = NULL;
text = (char*) malloc (11*sizeof(char));
if (text != NULL) // important!!!
{
strcpy (s, "SE is important");
printf ("%sn", text);
}
else
{
perror ("malloc");
abort ();
}
44
Allouer un string
char *text = NULL;
text = (char*) malloc (11*sizeof(char));
if (text != NULL) // important!!!
{
strcpy (s, "SE is important");
printf ("%sn", text);
/// ...
free (text);
text = NULL;
}
else
{
perror ("malloc");
abort ();
}
45
Fonctions pour string (pas sécurisé)
// string duplicate
char *strdup(const char *s1);
// string compare
int strcmp(const char *s1, const char *s2);
// string copy
char *strcpy(char *dest, const char *src);
// string concatenate
char *strcat(char *dest, const char *src);
// string length
size_t strlen(const char *s1);
46
Fonctions pour string (sécurisée)
// string duplicate (max n bytes)
char *strndup(const char *s1, size_t n);
// string compare (max n bytes)
int strncmp(const char *s1, const char *s2, size_t n);
// string copy (max n bytes)
char *strncpy(char *dest, const char *src, size_t n);
// string concatenate (max n bytes)
char *strncat(char *dest, const char *src, size_t n);
// string length (max n bytes)
size_t strnlen(const char *s1, size_t n);
47
Copier un string
char s[100];
strncpy (s, "", 99); // s = "”;
char s1[100];
char s2[100];
strncpy (s1, s2, 99); // s1 = s2;
48
Concaténer des strings
char s[200];
char s2[100];
strncat (s, s2, 99); // s = s + s2;
char s[200];
char s1[100];
char s2[100];
strncpy (s, s1, 99); // s = s1;
strncat (s, s2, 99); // s = s + s2;
49
Comparer les strings
char s1[100];
char s2[100];
// if (s1 == s2)
if (strncmp (s1, s2, 99) == 0)
// if (s1 < s2)
if (strncmp (s1, s2, 99) < 0)
// if (s1 > s2)
if (strncmp (s1, s2, 99) > 0)
50
STRUCTURES
51
Definition
#define MAX_NAME
// Type
struct File
{
char name[MAX_NAME+1];
long size;
};
// Variable
struct File file1;
52
Accéder aux membres
struct File file1;
strncpy (file1.name, "sde.txt", MAX_NAME);
file1.size = 50;
53
Pointeur sur une structure
struct File *file1 = NULL;
file1 = (struct File*)malloc ( ... ?);
54
Pointeur sur une structure
struct File *file1 = NULL;
file1 = (struct File*)malloc (sizeof(struct File));
55
Accès membre structure
struct File *file1 = NULL;
file1 = (struct File*)malloc (sizeof(struct File));
// pointer to a struct of type File
file1
// value from the memory location pointed by the pointer
*file1
// error, a pointer is an address, has no member
file1.name
// the value pointed is a struct that as a member
name
(*file1).name
56
Accès membre structure
// the value pointed is a struct
that as a member name
(*file1).name
file1->name
57
Pointeur sur une structure
struct File *file1 = NULL;
file1 = (struct File*)malloc (sizeof(struct File));
if (file1 != NULL)
{
strncpy ((*file1).name, "sde.txt", MAX_NAME);
(*file1).size = 50;
/// ...
free (file1);
file1 = NULL;
}
else
{
perror ("malloc");
abort ();
}
58
Pointeur sur une structure
struct File *file1 = NULL;
file1 = (struct File*)malloc (sizeof(struct File));
if (file1 != NULL)
{
strncpy (file1->name, "sde.txt", MAX_NAME);
file1->size = 50;
/// ...
free (file1);
file1 = NULL;
}
else
{
perror ("malloc");
abort ();
}
59
TAMPON DE DONNÉES
60
Fonctions pour la memoire
// compare memory
int memcmp(const void *m1, const void *m2, size_t n);
// copy memory
void *memcpy(void *dest, void *src, size_t n);
// set value
void *memset(void *b, int c, size_t n);
61
Tampon des donees
#define BUFFER_SIZE 1024
char buffer[BUFFER_SIZE];
// ...
// or
void *buffer = (void*)malloc (BUFFER_SIZE);
// ...
free (buffer);
62
Tampon des donees avec 0
char buffer[BUFFER_SIZE];
memset (buffer, 0, BUFFER_SIZE);
// ...
// or
void *buffer = (void*)calloc (1, BUFFER_SIZE);
// ...
free (buffer);
63
Exemple
int main ()
{
void *temp_buffer = (void*)malloc (1024);
void *buffer = (void*)malloc (1024);
int f = open ("data.bin", O_RDONLY);
read (f, temp_buffer, 1024);
memcpy (buffer, temp_buffer, 1024);
close (f);
return 0;
}
64
Curseur tampon
// at location 0
memcpy (buffer, data, n);
memcpy (&buffer[0], data, n);
// at location p
memcpy (&buffer[p], data, n);
65
Exemple avec curseur
#define PARTS 10
#define BUFFER_SIZE 1024
int main ()
{
void *temp_buffer = (void*)malloc (BUFFER_SIZE);
void *buffer = (void*)malloc (BUFFER_SIZE * PARTS);
int f = open ("data.bin", O_RDONLY);
int part, position = 0, bytes;
for (part = 0; part < PARTS; part++)
{
bytes = read (f, temp_buffer, BUFFER_SIZE);
if (bytes > 0)
{
memcpy (&buffer[position], temp_buffer, bytes);
position = position + bytes;
}
}
close (f);
return 0;
}
66
Tampon des donees avec 0
• la mémoire allouée n'est pas définie sur 0
• les données dans la mémoire nouvellement
allouée sont aléatoires
• Fonctions
– calloc - clear allocate
– strncpy - copy empty string
– memset - memory set
67
Mot clés
• Langage C
• ANSI C
• C90
• Libc
• gcc
• llvm
• Visual C++
• POSIX
• Macro
• Pointeur
• NULL
• allocation
• désallocation
• c-string
• structure
• tampon de données
• access dans le tampon
• valeur de retour
68
Bibliographie pour aujourd'hui
• Dan Gookin, C for Dummies (2nd Edition)
– Chapitre 6, 24, 27 et 29
• Peter D. Hipson, Advanced C
– Chapitre 2, 3, 7, 14 et 15
• Steve Summit, C Programming Notes
– Chapitre 6, 8, 9, 10 et 11
69
Questions
70

Contenu connexe

Tendances

SdE 4 - Processus
SdE 4 - ProcessusSdE 4 - Processus
SdE 4 - Processus
Alexandru Radovici
 
SdE 5 - Communication entre processus et Planification
SdE 5 - Communication entre processus et PlanificationSdE 5 - Communication entre processus et Planification
SdE 5 - Communication entre processus et Planification
Alexandru Radovici
 
Systemes d'explotation: Mémoire Virtuelle
Systemes d'explotation: Mémoire VirtuelleSystemes d'explotation: Mémoire Virtuelle
Systemes d'explotation: Mémoire Virtuelle
Alexandru Radovici
 
SdE 1 - Introduction
SdE 1 - IntroductionSdE 1 - Introduction
SdE 1 - Introduction
Alexandru Radovici
 
SdE 6 - Gestion de la memoire
SdE 6 - Gestion de la memoireSdE 6 - Gestion de la memoire
SdE 6 - Gestion de la memoire
Alexandru Radovici
 
SdE 11: Implémentation de Système de Fichiers
SdE 11: Implémentation de Système de FichiersSdE 11: Implémentation de Système de Fichiers
SdE 11: Implémentation de Système de Fichiers
Alexandru Radovici
 
SdE 8 - Synchronization de execution
SdE 8 - Synchronization de executionSdE 8 - Synchronization de execution
SdE 8 - Synchronization de execution
Alexandru Radovici
 
SdE 6 - Planification
SdE 6 - PlanificationSdE 6 - Planification
SdE 6 - Planification
Alexandru Radovici
 
SdE 2 - System de fichiers
SdE 2 - System de fichiersSdE 2 - System de fichiers
SdE 2 - System de fichiers
Alexandru Radovici
 
SdE 5 - Planification
SdE 5 - PlanificationSdE 5 - Planification
SdE 5 - Planification
Alexandru Radovici
 
SdE 8 - Synchronisation de execution
SdE 8 - Synchronisation de executionSdE 8 - Synchronisation de execution
SdE 8 - Synchronisation de execution
Alexandru Radovici
 
SdE 9 - Threads
SdE 9 - ThreadsSdE 9 - Threads
SdE 9 - Threads
Alexandru Radovici
 
SdE 8 - Memoire Virtuelle
SdE 8 - Memoire VirtuelleSdE 8 - Memoire Virtuelle
SdE 8 - Memoire Virtuelle
Alexandru Radovici
 
Présentation unix linux
Présentation unix linuxPrésentation unix linux
Présentation unix linux
Emmanuel Florac
 
SdE 7 - Gestion de la Mémoire
SdE 7 - Gestion de la MémoireSdE 7 - Gestion de la Mémoire
SdE 7 - Gestion de la Mémoire
Alexandru Radovici
 
Systemes d'explotation: Synchronization de execution
Systemes d'explotation: Synchronization de executionSystemes d'explotation: Synchronization de execution
Systemes d'explotation: Synchronization de execution
Alexandru Radovici
 
Formation Linux lpi 101
Formation Linux lpi 101 Formation Linux lpi 101
Formation Linux lpi 101
Kais Baccour
 
SdE 7 - Memoire Virtuelle
SdE 7 - Memoire VirtuelleSdE 7 - Memoire Virtuelle
SdE 7 - Memoire Virtuelle
Alexandru Radovici
 
SdE 2 - Introduction
SdE 2 - IntroductionSdE 2 - Introduction
SdE 2 - Introduction
Alexandru Radovici
 
lpi 101 notes de cours
lpi 101 notes de courslpi 101 notes de cours
lpi 101 notes de cours
ISIG
 

Tendances (20)

SdE 4 - Processus
SdE 4 - ProcessusSdE 4 - Processus
SdE 4 - Processus
 
SdE 5 - Communication entre processus et Planification
SdE 5 - Communication entre processus et PlanificationSdE 5 - Communication entre processus et Planification
SdE 5 - Communication entre processus et Planification
 
Systemes d'explotation: Mémoire Virtuelle
Systemes d'explotation: Mémoire VirtuelleSystemes d'explotation: Mémoire Virtuelle
Systemes d'explotation: Mémoire Virtuelle
 
SdE 1 - Introduction
SdE 1 - IntroductionSdE 1 - Introduction
SdE 1 - Introduction
 
SdE 6 - Gestion de la memoire
SdE 6 - Gestion de la memoireSdE 6 - Gestion de la memoire
SdE 6 - Gestion de la memoire
 
SdE 11: Implémentation de Système de Fichiers
SdE 11: Implémentation de Système de FichiersSdE 11: Implémentation de Système de Fichiers
SdE 11: Implémentation de Système de Fichiers
 
SdE 8 - Synchronization de execution
SdE 8 - Synchronization de executionSdE 8 - Synchronization de execution
SdE 8 - Synchronization de execution
 
SdE 6 - Planification
SdE 6 - PlanificationSdE 6 - Planification
SdE 6 - Planification
 
SdE 2 - System de fichiers
SdE 2 - System de fichiersSdE 2 - System de fichiers
SdE 2 - System de fichiers
 
SdE 5 - Planification
SdE 5 - PlanificationSdE 5 - Planification
SdE 5 - Planification
 
SdE 8 - Synchronisation de execution
SdE 8 - Synchronisation de executionSdE 8 - Synchronisation de execution
SdE 8 - Synchronisation de execution
 
SdE 9 - Threads
SdE 9 - ThreadsSdE 9 - Threads
SdE 9 - Threads
 
SdE 8 - Memoire Virtuelle
SdE 8 - Memoire VirtuelleSdE 8 - Memoire Virtuelle
SdE 8 - Memoire Virtuelle
 
Présentation unix linux
Présentation unix linuxPrésentation unix linux
Présentation unix linux
 
SdE 7 - Gestion de la Mémoire
SdE 7 - Gestion de la MémoireSdE 7 - Gestion de la Mémoire
SdE 7 - Gestion de la Mémoire
 
Systemes d'explotation: Synchronization de execution
Systemes d'explotation: Synchronization de executionSystemes d'explotation: Synchronization de execution
Systemes d'explotation: Synchronization de execution
 
Formation Linux lpi 101
Formation Linux lpi 101 Formation Linux lpi 101
Formation Linux lpi 101
 
SdE 7 - Memoire Virtuelle
SdE 7 - Memoire VirtuelleSdE 7 - Memoire Virtuelle
SdE 7 - Memoire Virtuelle
 
SdE 2 - Introduction
SdE 2 - IntroductionSdE 2 - Introduction
SdE 2 - Introduction
 
lpi 101 notes de cours
lpi 101 notes de courslpi 101 notes de cours
lpi 101 notes de cours
 

Similaire à SdE 2 - Langage C, Allocation de memoire

Cours C Avancé chapitre 2 et chapitre.pdf
Cours C Avancé  chapitre 2 et chapitre.pdfCours C Avancé  chapitre 2 et chapitre.pdf
Cours C Avancé chapitre 2 et chapitre.pdf
c79024186
 
Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)
Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)
Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)
Arnaud ASSAD ✅ Expert Open Source
 
Seance 4- Programmation en langage C
Seance 4- Programmation en langage CSeance 4- Programmation en langage C
Seance 4- Programmation en langage C
Fahad Golra
 
Interception de signal avec dump de la pile d'appel
Interception de signal avec dump de la pile d'appelInterception de signal avec dump de la pile d'appel
Interception de signal avec dump de la pile d'appel
Thierry Gayet
 
Formation python
Formation pythonFormation python
Formation python
Thierry Gayet
 
Cours de C++ / Tronc commun deuxième année ISIMA
Cours de C++ / Tronc commun deuxième année ISIMACours de C++ / Tronc commun deuxième année ISIMA
Cours de C++ / Tronc commun deuxième année ISIMA
Loic Yon
 
Introduction à Python
Introduction à PythonIntroduction à Python
Introduction à Python
Abdoulaye Dieng
 
COURS_PYTHON_22.ppt
COURS_PYTHON_22.pptCOURS_PYTHON_22.ppt
COURS_PYTHON_22.ppt
IbtissameAbbad1
 
Android Optimisations Greendroid
Android Optimisations GreendroidAndroid Optimisations Greendroid
Android Optimisations GreendroidGDG Nantes
 
De java à swift en 2 temps trois mouvements
De java à swift en 2 temps trois mouvementsDe java à swift en 2 temps trois mouvements
De java à swift en 2 temps trois mouvements
Didier Plaindoux
 
ALF 11 - Diagramme de flux de contrôle et WebAssembly
ALF 11 - Diagramme de flux de contrôle et WebAssemblyALF 11 - Diagramme de flux de contrôle et WebAssembly
ALF 11 - Diagramme de flux de contrôle et WebAssembly
Alexandru Radovici
 
Développement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulièresDéveloppement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulières
ECAM Brussels Engineering School
 
ALF 11 - Diagrame de flux de controlle
ALF 11 - Diagrame de flux de controlleALF 11 - Diagrame de flux de controlle
ALF 11 - Diagrame de flux de controlle
Alexandru Radovici
 
C1 - Langage C - ISIMA - Première partie
C1 - Langage C - ISIMA - Première partieC1 - Langage C - ISIMA - Première partie
C1 - Langage C - ISIMA - Première partie
Loic Yon
 
Présentation Javascript à l'ESI (Alger)
Présentation Javascript à l'ESI (Alger)Présentation Javascript à l'ESI (Alger)
Présentation Javascript à l'ESI (Alger)
Dr Samir A. ROUABHI
 
ALF 11 - WebAssembly
ALF 11 - WebAssemblyALF 11 - WebAssembly
ALF 11 - WebAssembly
Alexandru Radovici
 
Chap 1 Initiation.pptx
Chap 1 Initiation.pptxChap 1 Initiation.pptx
Chap 1 Initiation.pptx
olfaharrabi2
 
Chap 2--POO avec JAVA.pdf
Chap 2--POO avec JAVA.pdfChap 2--POO avec JAVA.pdf
Chap 2--POO avec JAVA.pdf
ramadanmahdi
 
Les nouveautés de C++11 : Ecrire du C++ Moderne
Les nouveautés de C++11 : Ecrire du C++ ModerneLes nouveautés de C++11 : Ecrire du C++ Moderne
Les nouveautés de C++11 : Ecrire du C++ Moderne
Microsoft
 
Exploiter php 5
Exploiter php 5Exploiter php 5
Exploiter php 5
halleck45
 

Similaire à SdE 2 - Langage C, Allocation de memoire (20)

Cours C Avancé chapitre 2 et chapitre.pdf
Cours C Avancé  chapitre 2 et chapitre.pdfCours C Avancé  chapitre 2 et chapitre.pdf
Cours C Avancé chapitre 2 et chapitre.pdf
 
Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)
Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)
Google Developer Group (GDG) Aix-Marseille #1 (27/08/2018)
 
Seance 4- Programmation en langage C
Seance 4- Programmation en langage CSeance 4- Programmation en langage C
Seance 4- Programmation en langage C
 
Interception de signal avec dump de la pile d'appel
Interception de signal avec dump de la pile d'appelInterception de signal avec dump de la pile d'appel
Interception de signal avec dump de la pile d'appel
 
Formation python
Formation pythonFormation python
Formation python
 
Cours de C++ / Tronc commun deuxième année ISIMA
Cours de C++ / Tronc commun deuxième année ISIMACours de C++ / Tronc commun deuxième année ISIMA
Cours de C++ / Tronc commun deuxième année ISIMA
 
Introduction à Python
Introduction à PythonIntroduction à Python
Introduction à Python
 
COURS_PYTHON_22.ppt
COURS_PYTHON_22.pptCOURS_PYTHON_22.ppt
COURS_PYTHON_22.ppt
 
Android Optimisations Greendroid
Android Optimisations GreendroidAndroid Optimisations Greendroid
Android Optimisations Greendroid
 
De java à swift en 2 temps trois mouvements
De java à swift en 2 temps trois mouvementsDe java à swift en 2 temps trois mouvements
De java à swift en 2 temps trois mouvements
 
ALF 11 - Diagramme de flux de contrôle et WebAssembly
ALF 11 - Diagramme de flux de contrôle et WebAssemblyALF 11 - Diagramme de flux de contrôle et WebAssembly
ALF 11 - Diagramme de flux de contrôle et WebAssembly
 
Développement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulièresDéveloppement informatique : Chaines de caractères et expressions regulières
Développement informatique : Chaines de caractères et expressions regulières
 
ALF 11 - Diagrame de flux de controlle
ALF 11 - Diagrame de flux de controlleALF 11 - Diagrame de flux de controlle
ALF 11 - Diagrame de flux de controlle
 
C1 - Langage C - ISIMA - Première partie
C1 - Langage C - ISIMA - Première partieC1 - Langage C - ISIMA - Première partie
C1 - Langage C - ISIMA - Première partie
 
Présentation Javascript à l'ESI (Alger)
Présentation Javascript à l'ESI (Alger)Présentation Javascript à l'ESI (Alger)
Présentation Javascript à l'ESI (Alger)
 
ALF 11 - WebAssembly
ALF 11 - WebAssemblyALF 11 - WebAssembly
ALF 11 - WebAssembly
 
Chap 1 Initiation.pptx
Chap 1 Initiation.pptxChap 1 Initiation.pptx
Chap 1 Initiation.pptx
 
Chap 2--POO avec JAVA.pdf
Chap 2--POO avec JAVA.pdfChap 2--POO avec JAVA.pdf
Chap 2--POO avec JAVA.pdf
 
Les nouveautés de C++11 : Ecrire du C++ Moderne
Les nouveautés de C++11 : Ecrire du C++ ModerneLes nouveautés de C++11 : Ecrire du C++ Moderne
Les nouveautés de C++11 : Ecrire du C++ Moderne
 
Exploiter php 5
Exploiter php 5Exploiter php 5
Exploiter php 5
 

Plus de Alexandru Radovici

SdE2 - Pilot Tock
SdE2 - Pilot TockSdE2 - Pilot Tock
SdE2 - Pilot Tock
Alexandru Radovici
 
SdE2 - Systèmes embarquées
SdE2 - Systèmes embarquéesSdE2 - Systèmes embarquées
SdE2 - Systèmes embarquées
Alexandru Radovici
 
SdE2 - Planification, IPC
SdE2 - Planification, IPCSdE2 - Planification, IPC
SdE2 - Planification, IPC
Alexandru Radovici
 
ALF1 - Introduction
ALF1 - IntroductionALF1 - Introduction
ALF1 - Introduction
Alexandru Radovici
 
SdE2 - Introduction
SdE2 - IntroductionSdE2 - Introduction
SdE2 - Introduction
Alexandru Radovici
 
MDAD 6 - AIDL and Services
MDAD 6 - AIDL and ServicesMDAD 6 - AIDL and Services
MDAD 6 - AIDL and Services
Alexandru Radovici
 
MDAD 5 - Threads
MDAD 5 - ThreadsMDAD 5 - Threads
MDAD 5 - Threads
Alexandru Radovici
 
MDAD 4 - Lists, adapters and recycling
MDAD 4 - Lists, adapters and recyclingMDAD 4 - Lists, adapters and recycling
MDAD 4 - Lists, adapters and recycling
Alexandru Radovici
 
MDAD 3 - Basics of UI Applications
MDAD 3 - Basics of UI ApplicationsMDAD 3 - Basics of UI Applications
MDAD 3 - Basics of UI Applications
Alexandru Radovici
 
MDAD 2 - Introduction to the Android Framework
MDAD 2 - Introduction to the Android FrameworkMDAD 2 - Introduction to the Android Framework
MDAD 2 - Introduction to the Android Framework
Alexandru Radovici
 
MDAD 1 - Hardware
MDAD 1 - HardwareMDAD 1 - Hardware
MDAD 1 - Hardware
Alexandru Radovici
 
MDAD 0 - Introduction
MDAD 0 - IntroductionMDAD 0 - Introduction
MDAD 0 - Introduction
Alexandru Radovici
 
SdE 11 - Reseau
SdE 11 - ReseauSdE 11 - Reseau
SdE 11 - Reseau
Alexandru Radovici
 
ALF 6 - Parser
ALF 6 - ParserALF 6 - Parser
ALF 6 - Parser
Alexandru Radovici
 
ALF 5 - Parser
ALF 5 - ParserALF 5 - Parser
ALF 5 - Parser
Alexandru Radovici
 
ALF 4 - Grammaires
ALF 4 - GrammairesALF 4 - Grammaires
ALF 4 - Grammaires
Alexandru Radovici
 
ALF 3 - Expressions régulières et Lexer
ALF 3 - Expressions régulières et LexerALF 3 - Expressions régulières et Lexer
ALF 3 - Expressions régulières et Lexer
Alexandru Radovici
 
ALF 1 - Automates finis
ALF 1 - Automates finis ALF 1 - Automates finis
ALF 1 - Automates finis
Alexandru Radovici
 
DAPM 1 - Introduction
DAPM 1 - IntroductionDAPM 1 - Introduction
DAPM 1 - Introduction
Alexandru Radovici
 
ALF 1 - Introduction
ALF 1 - IntroductionALF 1 - Introduction
ALF 1 - Introduction
Alexandru Radovici
 

Plus de Alexandru Radovici (20)

SdE2 - Pilot Tock
SdE2 - Pilot TockSdE2 - Pilot Tock
SdE2 - Pilot Tock
 
SdE2 - Systèmes embarquées
SdE2 - Systèmes embarquéesSdE2 - Systèmes embarquées
SdE2 - Systèmes embarquées
 
SdE2 - Planification, IPC
SdE2 - Planification, IPCSdE2 - Planification, IPC
SdE2 - Planification, IPC
 
ALF1 - Introduction
ALF1 - IntroductionALF1 - Introduction
ALF1 - Introduction
 
SdE2 - Introduction
SdE2 - IntroductionSdE2 - Introduction
SdE2 - Introduction
 
MDAD 6 - AIDL and Services
MDAD 6 - AIDL and ServicesMDAD 6 - AIDL and Services
MDAD 6 - AIDL and Services
 
MDAD 5 - Threads
MDAD 5 - ThreadsMDAD 5 - Threads
MDAD 5 - Threads
 
MDAD 4 - Lists, adapters and recycling
MDAD 4 - Lists, adapters and recyclingMDAD 4 - Lists, adapters and recycling
MDAD 4 - Lists, adapters and recycling
 
MDAD 3 - Basics of UI Applications
MDAD 3 - Basics of UI ApplicationsMDAD 3 - Basics of UI Applications
MDAD 3 - Basics of UI Applications
 
MDAD 2 - Introduction to the Android Framework
MDAD 2 - Introduction to the Android FrameworkMDAD 2 - Introduction to the Android Framework
MDAD 2 - Introduction to the Android Framework
 
MDAD 1 - Hardware
MDAD 1 - HardwareMDAD 1 - Hardware
MDAD 1 - Hardware
 
MDAD 0 - Introduction
MDAD 0 - IntroductionMDAD 0 - Introduction
MDAD 0 - Introduction
 
SdE 11 - Reseau
SdE 11 - ReseauSdE 11 - Reseau
SdE 11 - Reseau
 
ALF 6 - Parser
ALF 6 - ParserALF 6 - Parser
ALF 6 - Parser
 
ALF 5 - Parser
ALF 5 - ParserALF 5 - Parser
ALF 5 - Parser
 
ALF 4 - Grammaires
ALF 4 - GrammairesALF 4 - Grammaires
ALF 4 - Grammaires
 
ALF 3 - Expressions régulières et Lexer
ALF 3 - Expressions régulières et LexerALF 3 - Expressions régulières et Lexer
ALF 3 - Expressions régulières et Lexer
 
ALF 1 - Automates finis
ALF 1 - Automates finis ALF 1 - Automates finis
ALF 1 - Automates finis
 
DAPM 1 - Introduction
DAPM 1 - IntroductionDAPM 1 - Introduction
DAPM 1 - Introduction
 
ALF 1 - Introduction
ALF 1 - IntroductionALF 1 - Introduction
ALF 1 - Introduction
 

Dernier

SYLLABUS DU COURS MARKETING DTS 1-2.pdf
SYLLABUS DU COURS  MARKETING DTS 1-2.pdfSYLLABUS DU COURS  MARKETING DTS 1-2.pdf
SYLLABUS DU COURS MARKETING DTS 1-2.pdf
Moukagni Evrard
 
Exame DELF - A2 Francês pout tout public
Exame DELF - A2  Francês pout tout publicExame DELF - A2  Francês pout tout public
Exame DELF - A2 Francês pout tout public
GiselaAlves15
 
Projet de fin d'étude licence en sciece.pptx
Projet de fin d'étude licence en sciece.pptxProjet de fin d'étude licence en sciece.pptx
Projet de fin d'étude licence en sciece.pptx
elfangourabdelouahab
 
Cours SE - Gestion de la mémoire- Cours IG IPSET.pdf
Cours SE - Gestion de la mémoire- Cours IG IPSET.pdfCours SE - Gestion de la mémoire- Cours IG IPSET.pdf
Cours SE - Gestion de la mémoire- Cours IG IPSET.pdf
MedBechir
 
Newsletter SPW Agriculture en province du Luxembourg du 03-06-24
Newsletter SPW Agriculture en province du Luxembourg du 03-06-24Newsletter SPW Agriculture en province du Luxembourg du 03-06-24
Newsletter SPW Agriculture en province du Luxembourg du 03-06-24
BenotGeorges3
 
Méthodologie de recherche et de rédaction de mémoire.pptx
Méthodologie de recherche et de rédaction de mémoire.pptxMéthodologie de recherche et de rédaction de mémoire.pptx
Méthodologie de recherche et de rédaction de mémoire.pptx
LamoussaPaulOuattara1
 
Iris et les hommes.pptx
Iris      et         les      hommes.pptxIris      et         les      hommes.pptx
Iris et les hommes.pptx
Txaruka
 
Evaluación docentes "Un cielo, dos países: El camino de los descubrimientos"
Evaluación docentes "Un cielo, dos países: El camino de los descubrimientos"Evaluación docentes "Un cielo, dos países: El camino de los descubrimientos"
Evaluación docentes "Un cielo, dos países: El camino de los descubrimientos"
IES Turina/Rodrigo/Itaca/Palomeras
 
Mémoire de licence en finance comptabilité et audit
Mémoire de licence en finance comptabilité et auditMémoire de licence en finance comptabilité et audit
Mémoire de licence en finance comptabilité et audit
MelDjobo
 
Festival de Cannes 2024.pptx
Festival      de      Cannes     2024.pptxFestival      de      Cannes     2024.pptx
Festival de Cannes 2024.pptx
Txaruka
 
1-IMP-Tuto-Recherche simple avancée-V4-20240425-BS.pptx
1-IMP-Tuto-Recherche simple avancée-V4-20240425-BS.pptx1-IMP-Tuto-Recherche simple avancée-V4-20240425-BS.pptx
1-IMP-Tuto-Recherche simple avancée-V4-20240425-BS.pptx
schneiderbeatrice78
 
Calendrier du 3 juin 2024 et compte rendu.pdf
Calendrier du 3 juin 2024 et compte rendu.pdfCalendrier du 3 juin 2024 et compte rendu.pdf
Calendrier du 3 juin 2024 et compte rendu.pdf
frizzole
 
4 expositions à voir à Paris.pptx
4   expositions    à   voir   à Paris.pptx4   expositions    à   voir   à Paris.pptx
4 expositions à voir à Paris.pptx
Txaruka
 
M2i Webinar - « Participation Financière Obligatoire » et CPF : une opportuni...
M2i Webinar - « Participation Financière Obligatoire » et CPF : une opportuni...M2i Webinar - « Participation Financière Obligatoire » et CPF : une opportuni...
M2i Webinar - « Participation Financière Obligatoire » et CPF : une opportuni...
M2i Formation
 
Bilan schéma pour réun concertation SDLP V4.pptx
Bilan schéma pour réun concertation SDLP V4.pptxBilan schéma pour réun concertation SDLP V4.pptx
Bilan schéma pour réun concertation SDLP V4.pptx
bibliogard
 
Contrôle fiscale en république de guinée
Contrôle fiscale en république de guinéeContrôle fiscale en république de guinée
Contrôle fiscale en république de guinée
bangalykaba146
 

Dernier (16)

SYLLABUS DU COURS MARKETING DTS 1-2.pdf
SYLLABUS DU COURS  MARKETING DTS 1-2.pdfSYLLABUS DU COURS  MARKETING DTS 1-2.pdf
SYLLABUS DU COURS MARKETING DTS 1-2.pdf
 
Exame DELF - A2 Francês pout tout public
Exame DELF - A2  Francês pout tout publicExame DELF - A2  Francês pout tout public
Exame DELF - A2 Francês pout tout public
 
Projet de fin d'étude licence en sciece.pptx
Projet de fin d'étude licence en sciece.pptxProjet de fin d'étude licence en sciece.pptx
Projet de fin d'étude licence en sciece.pptx
 
Cours SE - Gestion de la mémoire- Cours IG IPSET.pdf
Cours SE - Gestion de la mémoire- Cours IG IPSET.pdfCours SE - Gestion de la mémoire- Cours IG IPSET.pdf
Cours SE - Gestion de la mémoire- Cours IG IPSET.pdf
 
Newsletter SPW Agriculture en province du Luxembourg du 03-06-24
Newsletter SPW Agriculture en province du Luxembourg du 03-06-24Newsletter SPW Agriculture en province du Luxembourg du 03-06-24
Newsletter SPW Agriculture en province du Luxembourg du 03-06-24
 
Méthodologie de recherche et de rédaction de mémoire.pptx
Méthodologie de recherche et de rédaction de mémoire.pptxMéthodologie de recherche et de rédaction de mémoire.pptx
Méthodologie de recherche et de rédaction de mémoire.pptx
 
Iris et les hommes.pptx
Iris      et         les      hommes.pptxIris      et         les      hommes.pptx
Iris et les hommes.pptx
 
Evaluación docentes "Un cielo, dos países: El camino de los descubrimientos"
Evaluación docentes "Un cielo, dos países: El camino de los descubrimientos"Evaluación docentes "Un cielo, dos países: El camino de los descubrimientos"
Evaluación docentes "Un cielo, dos países: El camino de los descubrimientos"
 
Mémoire de licence en finance comptabilité et audit
Mémoire de licence en finance comptabilité et auditMémoire de licence en finance comptabilité et audit
Mémoire de licence en finance comptabilité et audit
 
Festival de Cannes 2024.pptx
Festival      de      Cannes     2024.pptxFestival      de      Cannes     2024.pptx
Festival de Cannes 2024.pptx
 
1-IMP-Tuto-Recherche simple avancée-V4-20240425-BS.pptx
1-IMP-Tuto-Recherche simple avancée-V4-20240425-BS.pptx1-IMP-Tuto-Recherche simple avancée-V4-20240425-BS.pptx
1-IMP-Tuto-Recherche simple avancée-V4-20240425-BS.pptx
 
Calendrier du 3 juin 2024 et compte rendu.pdf
Calendrier du 3 juin 2024 et compte rendu.pdfCalendrier du 3 juin 2024 et compte rendu.pdf
Calendrier du 3 juin 2024 et compte rendu.pdf
 
4 expositions à voir à Paris.pptx
4   expositions    à   voir   à Paris.pptx4   expositions    à   voir   à Paris.pptx
4 expositions à voir à Paris.pptx
 
M2i Webinar - « Participation Financière Obligatoire » et CPF : une opportuni...
M2i Webinar - « Participation Financière Obligatoire » et CPF : une opportuni...M2i Webinar - « Participation Financière Obligatoire » et CPF : une opportuni...
M2i Webinar - « Participation Financière Obligatoire » et CPF : une opportuni...
 
Bilan schéma pour réun concertation SDLP V4.pptx
Bilan schéma pour réun concertation SDLP V4.pptxBilan schéma pour réun concertation SDLP V4.pptx
Bilan schéma pour réun concertation SDLP V4.pptx
 
Contrôle fiscale en république de guinée
Contrôle fiscale en république de guinéeContrôle fiscale en république de guinée
Contrôle fiscale en république de guinée
 

SdE 2 - Langage C, Allocation de memoire

  • 4. Dennis Ritchie • Américain • Harvard University • Auteur de langage C • Co-auteur UNIX 4
  • 5. Contenu • Le langage C • Le standard POSIX • Allocation de mémoire 5
  • 6. Bibliographie pour aujourd'hui • Dan Gookin, C for Dummies (2nd Edition) – Chapitre 6, 24, 27 et 29 • Peter D. Hipson, Advanced C – Chapitre 2, 3, 7, 14 et 15 • Steve Summit, C Programming Notes – Chapitre 6, 8, 9, 10 et 11 6
  • 8. Langage C • Ecrit par Denis Ritchie, 1972 • Bell Labs • A été écrit pour UNIX • Portable – Fonction sur presque toutes SE • Macro Assembleur • Fichiers .h et .c • Diffèrent de C++ 8
  • 9. Standards C • Original – K&R C • Plus utilisé ANSI C (C89 ou C90) • Plus stricte C99 – Plus de types des données • Plus nouveau C11 et C18 • Embedded C 9
  • 10. Bibliothèque C • Libc – fonctions qui sont disponible dans toutes les SE • Pour un nouveau SE, c’est la premier bibliothèque implémenté • Exemple – printf / scanf – malloc / free – fopen / fread 10
  • 11. Compilateurs pour le langage C • GNU Compiler Collection (gcc) • Low Level Virtual Machine (llvm - clang) • Microsoft Visual C++ (msvc) • Intel C 11
  • 12. La structure d’un program en C // defines #define VALUE 10000 ... // variables declaration int main () { // variables declaration // statements (code) return 0; } int f () { // variables declaration // statements (code) } 12
  • 14. POSIX • Standard • Portable Operating System Interface • POSIX – 1 – comprend ANSI C • POSIX – 1b – Temps Réel • POSIX – 1c - Fils d’exécutions • POSIX -2 – Shell et outilles 14
  • 15. SE conformes avec POSIX 15
  • 17. Macro Definition #define SIZE 1000; long vector[SIZE]; 17
  • 18. Macro après la Compilation long vector[1000;]; 18 Erreur
  • 19. Macro Definition #define SIZE 1000 long vector[SIZE]; 19
  • 20. Macro après la Compilation long vector[1000]; 20
  • 21. Utilisation des Macros • Utilisé pour définition de constants • Paramétriez le programme • Modifier les valeurs en un seul endroit 21
  • 23. Disposition de la mémoire 23
  • 25. La memoire en C • Pointeurs – nom, adresse, adresse référencée • Valeur – adresse de mémoire (numéro) – NULL (numéro 0) • Fonctions – sizeof – malloc – calloc – realloc – free 25
  • 26. Valeur NULL • Valeur 0 #define NULL ((void*)0) • Protection – La adresse 0 n’est pas utilise 26
  • 27. sizeof operateur sizeof (data) data – variable ou type de données Renvoie le nombre d'octets occupés par data 27
  • 28. sizeof • sizeof (short) ? – 2 • sizeof (char) ? – 1 • sizeof (long) ? – 4 • sizeof (int) ? – 4 ou 8 • sizeof (long long) ? – 8 • int f; sizeof (f) ? – 4 ou 8 28
  • 29. malloc void *malloc (size_t size); size - nombre de octets demandée renvoie: • Succès: pointeur vers la mémoriel allouée • Erreur: NULL La mémoire alloue n’a pas toujours la valeur 0 int *s = (int*)malloc (sizeof (int)) pourquoi pas sizeof (4)? 29
  • 30. calloc void *calloc (size_t count, size_t size); count – nombre d'objets à allouer size – taille en octets d'objets à allouer renvoie: • Succès: pointeur vers la mémoriel allouée • Erreur: NULL La mémoire alloue este avec la valeur 0 // one item int *s = (int*)calloc (1, sizeof (int)); // array of items int *v = (int*)calloc (100, sizeof (int)); 30
  • 31. realloc void *realloc (void *ptr, size_t size); ptr - pointeur précédemment alloue size - nombre nouveau de octets demandée renvoie: • Succès: pointeur vers la nouveau mémoriel allouée • Erreur: NULL La mémoire nouveau alloue n’a pas toujours la valeur 0 // resize the s array s = (int*)realloc (s, 100*sizeof(int)); 31
  • 32. free void free (void *ptr); ptr - pointeur à libérer free (s); // s does not become NULL s = NULL; // important ptr ne change pas sa valeur en NULL 32
  • 33. Fuite de mémoire Il n'y a aucun moyen de libérer un pointeur int *p = (int*)malloc (sizeof(int)); … p = NULL; // p is leaked 33 Valgrind valgrind.org
  • 34. malloc – vérifiez le retour int *s = (int*) malloc (sizeof (int)) if (s != NULL) { … } else { perror ("malloc"); abort (); } 34
  • 35. Déréférencer un pointeur int a = 510; int *p = NULL; p = &a; // &a - address of variable a printf ("%dn", a); // prints 510 printf ("%dn", p); // prints the address of a printf ("%dn", *p); // prints 510 (the value at the address of a) 35
  • 36. Déréférencer un pointeur int *a = NULL; a = (int*)malloc (sizeof(int)); if (a != NULL) { *a = 510; printf ("%dn", a); // prints ...? printf ("%dn", *a); // prints ...? free (a); a = NULL; } else { perror ("malloc"); abort (); } 36
  • 37. Déréférencer un pointeur int *a = NULL; a = (int*)malloc (sizeof(int)); if (a != NULL) { *a = 510; printf ("%dn", a); // prints the address of a printf ("%dn", *a); // prints 510 free (a); a = NULL; } else { perror ("malloc"); abort (); } 37
  • 39. String - C Style s t r i n g 0 … 115 116 114 105 110 103 0 … char s[N] N 39
  • 40. Déclaration pour string char s[100]; // use s char *s = NULL; s = (char*)malloc ( ... ? ); // use s free (s); s = NULL; 40
  • 41. Déclaration pour string char s[100]; // use s char *s = NULL; s = (char*)malloc (100*sizeof(char)); // use s free (s); s = NULL; 41
  • 42. Déclaration pour string char s[100]; // use s char *s = NULL; s = (char*)calloc (100, sizeof(char)); // use s free (s); s = NULL; 42
  • 43. Allouer un string text <- "SE subject" char *text = NULL; text = (char*) malloc (…) strncpy (text, "SE subject", ...); 43
  • 44. Allouer un string text <- "SE subject" char *text = NULL; text = (char*) malloc (11*sizeof(char)); if (text != NULL) // important!!! { strcpy (s, "SE is important"); printf ("%sn", text); } else { perror ("malloc"); abort (); } 44
  • 45. Allouer un string char *text = NULL; text = (char*) malloc (11*sizeof(char)); if (text != NULL) // important!!! { strcpy (s, "SE is important"); printf ("%sn", text); /// ... free (text); text = NULL; } else { perror ("malloc"); abort (); } 45
  • 46. Fonctions pour string (pas sécurisé) // string duplicate char *strdup(const char *s1); // string compare int strcmp(const char *s1, const char *s2); // string copy char *strcpy(char *dest, const char *src); // string concatenate char *strcat(char *dest, const char *src); // string length size_t strlen(const char *s1); 46
  • 47. Fonctions pour string (sécurisée) // string duplicate (max n bytes) char *strndup(const char *s1, size_t n); // string compare (max n bytes) int strncmp(const char *s1, const char *s2, size_t n); // string copy (max n bytes) char *strncpy(char *dest, const char *src, size_t n); // string concatenate (max n bytes) char *strncat(char *dest, const char *src, size_t n); // string length (max n bytes) size_t strnlen(const char *s1, size_t n); 47
  • 48. Copier un string char s[100]; strncpy (s, "", 99); // s = "”; char s1[100]; char s2[100]; strncpy (s1, s2, 99); // s1 = s2; 48
  • 49. Concaténer des strings char s[200]; char s2[100]; strncat (s, s2, 99); // s = s + s2; char s[200]; char s1[100]; char s2[100]; strncpy (s, s1, 99); // s = s1; strncat (s, s2, 99); // s = s + s2; 49
  • 50. Comparer les strings char s1[100]; char s2[100]; // if (s1 == s2) if (strncmp (s1, s2, 99) == 0) // if (s1 < s2) if (strncmp (s1, s2, 99) < 0) // if (s1 > s2) if (strncmp (s1, s2, 99) > 0) 50
  • 52. Definition #define MAX_NAME // Type struct File { char name[MAX_NAME+1]; long size; }; // Variable struct File file1; 52
  • 53. Accéder aux membres struct File file1; strncpy (file1.name, "sde.txt", MAX_NAME); file1.size = 50; 53
  • 54. Pointeur sur une structure struct File *file1 = NULL; file1 = (struct File*)malloc ( ... ?); 54
  • 55. Pointeur sur une structure struct File *file1 = NULL; file1 = (struct File*)malloc (sizeof(struct File)); 55
  • 56. Accès membre structure struct File *file1 = NULL; file1 = (struct File*)malloc (sizeof(struct File)); // pointer to a struct of type File file1 // value from the memory location pointed by the pointer *file1 // error, a pointer is an address, has no member file1.name // the value pointed is a struct that as a member name (*file1).name 56
  • 57. Accès membre structure // the value pointed is a struct that as a member name (*file1).name file1->name 57
  • 58. Pointeur sur une structure struct File *file1 = NULL; file1 = (struct File*)malloc (sizeof(struct File)); if (file1 != NULL) { strncpy ((*file1).name, "sde.txt", MAX_NAME); (*file1).size = 50; /// ... free (file1); file1 = NULL; } else { perror ("malloc"); abort (); } 58
  • 59. Pointeur sur une structure struct File *file1 = NULL; file1 = (struct File*)malloc (sizeof(struct File)); if (file1 != NULL) { strncpy (file1->name, "sde.txt", MAX_NAME); file1->size = 50; /// ... free (file1); file1 = NULL; } else { perror ("malloc"); abort (); } 59
  • 61. Fonctions pour la memoire // compare memory int memcmp(const void *m1, const void *m2, size_t n); // copy memory void *memcpy(void *dest, void *src, size_t n); // set value void *memset(void *b, int c, size_t n); 61
  • 62. Tampon des donees #define BUFFER_SIZE 1024 char buffer[BUFFER_SIZE]; // ... // or void *buffer = (void*)malloc (BUFFER_SIZE); // ... free (buffer); 62
  • 63. Tampon des donees avec 0 char buffer[BUFFER_SIZE]; memset (buffer, 0, BUFFER_SIZE); // ... // or void *buffer = (void*)calloc (1, BUFFER_SIZE); // ... free (buffer); 63
  • 64. Exemple int main () { void *temp_buffer = (void*)malloc (1024); void *buffer = (void*)malloc (1024); int f = open ("data.bin", O_RDONLY); read (f, temp_buffer, 1024); memcpy (buffer, temp_buffer, 1024); close (f); return 0; } 64
  • 65. Curseur tampon // at location 0 memcpy (buffer, data, n); memcpy (&buffer[0], data, n); // at location p memcpy (&buffer[p], data, n); 65
  • 66. Exemple avec curseur #define PARTS 10 #define BUFFER_SIZE 1024 int main () { void *temp_buffer = (void*)malloc (BUFFER_SIZE); void *buffer = (void*)malloc (BUFFER_SIZE * PARTS); int f = open ("data.bin", O_RDONLY); int part, position = 0, bytes; for (part = 0; part < PARTS; part++) { bytes = read (f, temp_buffer, BUFFER_SIZE); if (bytes > 0) { memcpy (&buffer[position], temp_buffer, bytes); position = position + bytes; } } close (f); return 0; } 66
  • 67. Tampon des donees avec 0 • la mémoire allouée n'est pas définie sur 0 • les données dans la mémoire nouvellement allouée sont aléatoires • Fonctions – calloc - clear allocate – strncpy - copy empty string – memset - memory set 67
  • 68. Mot clés • Langage C • ANSI C • C90 • Libc • gcc • llvm • Visual C++ • POSIX • Macro • Pointeur • NULL • allocation • désallocation • c-string • structure • tampon de données • access dans le tampon • valeur de retour 68
  • 69. Bibliographie pour aujourd'hui • Dan Gookin, C for Dummies (2nd Edition) – Chapitre 6, 24, 27 et 29 • Peter D. Hipson, Advanced C – Chapitre 2, 3, 7, 14 et 15 • Steve Summit, C Programming Notes – Chapitre 6, 8, 9, 10 et 11 69