C snippets and C FAQ🔗
Introduction
I love C! It used to be one of the first language I have learnt when I was a child. Even if C is a very easy to learn language, it demands lots of practice to avoid common mistakes. If you are a daily C developper, you will be able to easily remember all of the tricks involved in practicing C.
As I can't be a daily C programmer, I keep this page in order to remember things I have discovered on this fascinating language. Some of them seem trivials but it doesn't harm to start from the basics.
Bytes and char
- unsigned char is for bytes (raw data).
- char is for strings.
Allocation
- It is not possible to grab the size of an allocated pointer with sizeof.
- You have to keep the length either a constant or in a dedicated variable.
- sizeof(array) will return the size in bytes for the array.
- use sizeof(array)/sizeof(array[0]) to find the number of elements of the array.
- Be careful with realloc: always ensure to use a pointer to a pointer as an argument for the function which will deal with reallocation. Otherwise, most of the time you will suffer with double free corruption because the reallocated pointer is local.
True or False
- True is non-zero!
- False is zero.
Strings
- In snprintf, the size argument does include the trailing (NULL) character.
Sockets and network
- Don't use gethostbyname, use getaddrinfo instead. It does manage IPv6 much simpler than the previous libc version with gethostbyname.
- Read the good introduction on sockets on Beej's Guide to Network Programming.