class: lead
Résumé concis des notions essentielles pour le cours
Makefile
compiler-first-c-debian12.md
prerequis-rappels-c.md
seance1-outillage-qualite.md
char
short
int
long
long long
float
double
_Bool
const
volatile
static
extern
sizeof
stdint.h
if
else
switch
for
while
do
{}
enum
struct
.h
.c
#ifndef / #define / #endif
#pragma once
inline
int *p
char s[]
const char *msg
int a[10]; int *p = a; // p == &a[0]
int a[10]; int *p = a; // équivalent à &a[0] printf("sizeof(a) = %zu, sizeof(p) = %zu\n", sizeof(a), sizeof(p)); // sizeof(a) == 10 * sizeof(int) (si utilisé dans le même scope) // sizeof(p) == taille d'un pointeur (ex. 8)
void f(int *p)
p
size_t n
sizeof(a)
&a
int (*)[N]
sizeof(a)/sizeof a[0]
sizeof(p)/sizeof p[0]
int *arr = malloc(n * sizeof *arr); if (!arr) return NULL; // gérer l'erreur // ... free(arr);
malloc
calloc
free()
realloc
-Wall -Wextra -Werror -Wconversion -g -O2
printf
-Wall -Wextra -Werror
int sum(const int *a, size_t n)
n==0
/* const correctness */ void foo(const int *p); // ne modifie pas *p void bar(int * const p); // p ne change pas, *p peut changer /* Pointeur vers pointeur : créer une chaîne dupliquée */ char *strdup_safe(const char *s) { if (!s) return NULL; size_t n = strlen(s) + 1; char *d = malloc(n); if (!d) return NULL; memcpy(d, s, n); return d; // ownership transferred to caller }
void *safe_realloc(void *ptr, size_t new_size) { void *tmp = realloc(ptr, new_size); if (!tmp) { // realloc failed, original ptr still valid return NULL; } return tmp; } /* Utilisation */ int *arr = malloc(n * sizeof *arr); int *tmp = safe_realloc(arr, (n2) * sizeof *arr); if (!tmp) { free(arr); // gérer l'erreur } else { arr = tmp; }
goto cleanup
int do_work(void) { int ret = -1; char *buf = NULL; FILE *f = NULL; buf = malloc(1024); if (!buf) goto out; f = fopen("data.bin", "rb"); if (!f) goto out; // ... traiter ret = 0; // succès out: if (f) fclose(f); free(buf); return ret; }
snprintf
strnlen
memmove
strcpy/strcat
char dst[32]; int n = snprintf(dst, sizeof dst, "%s %d", name, value); if (n < 0 || (size_t)n >= sizeof dst) { // erreur ou troncature } /* memmove pour zones qui se chevauchent */ memmove(dst + 2, dst, 10);
#include <stdint.h> #include <limits.h> bool sum_safe(const int *a, size_t n, int *out) { if (!a || !out) return false; int64_t acc = 0; for (size_t i = 0; i < n; ++i) { acc += (int64_t)a[i]; if (acc > INT_MAX || acc < INT_MIN) return false; // overflow } *out = (int)acc; return true; }
assert
#include <assert.h> void test_sum(void) { int a[] = {1,2,3}; int out; assert(sum_safe(a, 3, &out) && out == 6); } int main(void) { test_sum(); return 0; }
Diagramme Mermaid pré-rendu (SVG)