I usually initialize all my data structure pointers to null. Then if an error occurs I first print an error message, and then call a killall function that releases the memory. eg suppose there is a data structure called 'mesh'
Code:
typedef struct mesh
{
int ntri, int nvert;
triangle *tri; /* triangle array */
vector *vert; /* vertex array */
}mesh;
mesh *m_ptr;
Code:
void killall()
{
killmesh();
...
...
}
void killmesh()
{
if (m_ptr != NULL)
{
if (m_ptr->vert != NULL)
{
free(m_ptr->vert);
}
if (m_ptr->tri != NULL)
{
free(m_ptr->tri);
}
free(m_ptr);
}
}
I've heard that in situations like this if you directly free memory of m_ptr for eg. without freeing m_ptr->vert and m_ptr->tri, it can result in memory leaks.