Theory
Common mistakes
Memory errors are most dangerous because under MinGW the program often "works". GitHub CI with ASan catches them.
Common mistakes
- An unchecked
malloc/realloc. OnNULL,p[0] = 1writes into nowhere. After every one –if (p == NULL). p = realloc(p, ...). OnNULLthe old block is lost and can never be freed. Into a temporary pointer first.malloc(n)instead ofmalloc(n * sizeof *p). 10intis 40 bytes, not 10. ASan:heap-buffer-overflow.- A forgotten
'\0'. A copy of a string needsstrlen(s) + 1bytes. - Memory never freed.
LeakSanitizer: detected memory leaks. Especially on an earlyreturnafter an error:group_freeis needed there too. - Use after
free. The pointer still holds the address, but the block isn't yours. ASan:heap-use-after-free; when thefreeand the use are in the same function, CI's GCC already stops at compile time:pointer ‘p’ used after ‘free’. Afterfree–p = NULL. freetwice. ASan:attempting double-free(when the twofreecalls are in different functions; in the same function CI's GCC refuses to compile it:used after ‘free’).p = NULLafterfreeprotects here too:free(NULL)does nothing.freeon somethingmallocdidn't give.free(&x)orfree(p + 1)– undefined behaviour.- Old pointers after
realloc.int *first = &m.data[0];and thenarray_add– after a move,firstpoints at freed memory. sizeof pinstead of the capacity. A pointer is 8 bytes, however many elements are behind it. Keep the count yourself (count,capacity).