| GNOME Programming Guidelines | |||
|---|---|---|---|
| <<< Previous | Home | ||
Take a look at the Mozilla bug lists and one thing is clear: new code that enters Mozilla is not (or has not been) sufficiently checked for memory leaks and access trouble.
Memory leaks are bad for several reasons:
They'll eat your swap space slowly. Eventually your program or even your machine will be brought to its knees.
You don't want to give your program or library a bloat-ware reputation just because you were lazy. Leave that to people in Redmont.
They hide bad use of memory. If you forget to free memory, there really is no way to catch reads and writes to that chunk of memory. If you later fix the leak, a completely different part of the program could go *poof*.
When using automatic memory checkers, you don't want to see 600 problems, 500 of which in support libraries. You really want to know that things were by and large clean before you started messing, and therefore that all the problems are yours to fix.
This is one of Mozilla's problems right now: it leaks like crazy so how are you ever going to know if you just added to the problem?
Use "const" whenever you can (for pointers that is).
If an argument is "const", then undoubtedly the function you call will not free it for you.
If a function result type is "const", then clearly you are not responsible for freeing it. You *probably* are for a non-"const" result (that isn't just an integer or some such).
Note, that unfortunately this does not work very well with ref-counted objects. It works great with strings.
Since C uses call-by-value, there is no point in making ints, doubles, and such types "const".
Document responsibilities.
If a function takes ownership of an object/ref, be explicit about it.
Always say if the caller should free/unref results.
Document *how* to get rid of memory: unref, free, g_free, ...
Be careful when using cut-and-paste.
The process of cutting and pasting does not improve code, contrary to the belief of many programmers. Please look the code over first, and if you intend to produce many copies, then perhaps you need a helper function.
Free everything at exit.
This takes time, so perhaps you should only do this within a conditional.
The reason for this piece of advice is that memory leak checkers have a hard time distinguishing between leaks you know and don't care about and other leaks.
Don't leave dangling pointers in your data structures.
Assign NULL or (void *)0xdeadbeef to freed members unless you are going to free the structure they are in right away.
Dangling pointers have a bad tendency of shielding leaks.
Run your new code a million times in a loop.
If it leaks, you'll know -- just follow the process with top in another window.
Fix it now, not later.
Do not write sloppy code; it will get back to you later.
| <<< Previous | Home | ||
| Maintaining a Package | |||