diff options
| author | Andrew Clayton <ac@sigsegv.uk> | 2025-03-07 00:07:25 +0000 |
|---|---|---|
| committer | Andrew Clayton <ac@sigsegv.uk> | 2025-03-07 00:07:25 +0000 |
| commit | 891c8fbd0c825b6716225e778a8f013afb858d57 (patch) | |
| tree | 2b98bc47b6db420b10017ca4c0100e6abacd8cc8 /examples | |
| download | common_c_mistakes-master.tar.gz common_c_mistakes-master.tar.bz2 | |
Signed-off-by: Andrew Clayton <ac@sigsegv.uk>
Diffstat (limited to '')
| -rw-r--r-- | examples/empty-func-args.c | 4 | ||||
| -rw-r--r-- | examples/malloc-cast.c | 4 | ||||
| -rw-r--r-- | examples/pass-by-value.c | 41 | ||||
| -rw-r--r-- | examples/strsep-invalid-free.c | 16 |
4 files changed, 65 insertions, 0 deletions
diff --git a/examples/empty-func-args.c b/examples/empty-func-args.c new file mode 100644 index 0000000..8093c22 --- /dev/null +++ b/examples/empty-func-args.c @@ -0,0 +1,4 @@ +void f() +{ + /* Do something */ +} diff --git a/examples/malloc-cast.c b/examples/malloc-cast.c new file mode 100644 index 0000000..5015147 --- /dev/null +++ b/examples/malloc-cast.c @@ -0,0 +1,4 @@ +void f(void) +{ + int *vals = malloc(sizeof(int) * 10); +} diff --git a/examples/pass-by-value.c b/examples/pass-by-value.c new file mode 100644 index 0000000..c452591 --- /dev/null +++ b/examples/pass-by-value.c @@ -0,0 +1,41 @@ +#include <stdio.h> +#include <stdlib.h> + +struct s { + int i; +}; + +static void fv(struct s *s) +{ + /* Do something with s */ + + free(s); + s = NULL; +} + +static void fr(struct s **s) +{ + /* Do something with s */ + + free(*s); + *s = NULL; +} + +int main(void) +{ + struct s *s; + + s = malloc(sizeof(*s)); + printf("s: %p\n", s); + fv(s); + printf("s: %p\n", s); + + printf("\n"); + + s = malloc(sizeof(*s)); + printf("s: %p\n", s); + fr(&s); + printf("s: %p\n", s); + + return 0; +} diff --git a/examples/strsep-invalid-free.c b/examples/strsep-invalid-free.c new file mode 100644 index 0000000..e01685d --- /dev/null +++ b/examples/strsep-invalid-free.c @@ -0,0 +1,16 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +int main(void) +{ + char *str = strdup("Hello World"), *tkn; + + printf("str [%s@%p]\n", str, str); + tkn = strsep(&str, " "); + printf("tkn [%s] str [%s@%p]\n", tkn, str, str); + + free(str); + + return 0; +} |
