I was looking for some guidelines on the net for safely managing memory allocation/deallocation on C. But could not find some good sources.
I thought maybe it is a good idea to pile up one, maybe on this site. I could start with some, to indicate what I mean, maybe someone can "improve" it, so that we have a full list of guidelines which help us ensure (to the maximum extent) we manage memory properly.
Example :
Always initialize pointers when declared.
int*p = NULL;
Check return type of malloc
int *p = malloc(sizeof(int)); if(p==NULL) { /* do some error handling*/ }
Each
malloc
should have correspondingfree
Possible problem is to free memory twice. How to avoid that? Assign pointer NULL after deletion.
free(p); p=NULL;
note: As pointed in comments, this does not protect if an object had two pointers. And it was already freed using one of the pointers.
- Another possible problem is to free memory which contains some garbage or free memory not allocated by malloc. How to avoid that? AFAIAC this is not easy to check. Given programmer follows previous steps, he/she should additionally check no random/bad memory gets assigned to pointer.
Otherwise, if one follows these guidelines this seems pretty safe way to manage memory for me.
Any ideas? Suggestions?