A common mistake using realloc is that people think realloc always free the old memory block. This is not always true:
Code:
char *t;
if((t = malloc(1024)) == NULL)
{
/* error handling */
}
if((t = realloc(t, 1024 * 2)) == NULL)
{
/* damn, realloc failed but old memory chunk is still allocated */
/* and I have nothing pointing to it -> memory leak */
}
Better to do it this way:
Code:
char *t;
char *tmp;
if((t = malloc(1024)) == NULL)
{
/* error handling */
}
if((tmp = realloc(t, 1024 * 2)) == NULL)
{
/* t is still pointing to 1024 bytes allocated memory */
}else
{
/* t is now pointing to nothing and tmp to 2048 bytes allocated memory */
}