originallly:
http://stackoverflow.com/questions/27451220/how-can-i-correctly-handle-malloc-failure-in-c-especially-when-there-is-more-th
//version 1
int function()
{
void *x,*y,*z;
x = malloc(10);
if (!x)
goto error1;
y = malloc(20);
if (!y)
goto error2;
z = malloc(50);
if (!z)
goto error3;
goto out;
error3:
free(y);
error2:
free(x);
error1:
return ERROR;
out:
return 0;
}
// version 1 making too much noise. There is absolutely NO issue in freeing a NULL pointer.
// version 2
int function()
{
void *x,*y,*z;
ret = 0;
x = malloc(10);
y = malloc(20);
z = malloc(50);
if (!x || !y || !z) {
ret = ERROR;
}
free(z);
free(y);
free(x);
return ret; // Here I have the assumption that caller is NOT looking
// for x,y,z memory access. Look version 3. if caller needs x,y,z
}
//version 3 - memory required by caller
int function()
{
void *x = *y = *z = NULL;
ret = 0;
x = malloc(10);
y = malloc(20);
z = malloc(50);
if (!x || !y || !z) {
ret = ERROR;
goto error;
} else {
goto out;
}
error:
free(z);
free(y);
free(x);
out:
return ret;
}
//version 4 - removing goto's - memory required by caller
int function()
{
void *x = *y = *z = NULL;
ret = 0;
x = malloc(10);
y = malloc(20);
z = malloc(50);
if (!x || !y || !z) {
ret = ERROR;
free(z);
free(y);
free(x);
}
return ret;
}
http://stackoverflow.com/questions/27451220/how-can-i-correctly-handle-malloc-failure-in-c-especially-when-there-is-more-th
//version 1
int function()
{
void *x,*y,*z;
x = malloc(10);
if (!x)
goto error1;
y = malloc(20);
if (!y)
goto error2;
z = malloc(50);
if (!z)
goto error3;
goto out;
error3:
free(y);
error2:
free(x);
error1:
return ERROR;
out:
return 0;
}
// version 1 making too much noise. There is absolutely NO issue in freeing a NULL pointer.
// version 2
int function()
{
void *x,*y,*z;
ret = 0;
x = malloc(10);
y = malloc(20);
z = malloc(50);
if (!x || !y || !z) {
ret = ERROR;
}
free(z);
free(y);
free(x);
return ret; // Here I have the assumption that caller is NOT looking
// for x,y,z memory access. Look version 3. if caller needs x,y,z
}
//version 3 - memory required by caller
int function()
{
void *x = *y = *z = NULL;
ret = 0;
x = malloc(10);
y = malloc(20);
z = malloc(50);
if (!x || !y || !z) {
ret = ERROR;
goto error;
} else {
goto out;
}
error:
free(z);
free(y);
free(x);
out:
return ret;
}
//version 4 - removing goto's - memory required by caller
int function()
{
void *x = *y = *z = NULL;
ret = 0;
x = malloc(10);
y = malloc(20);
z = malloc(50);
if (!x || !y || !z) {
ret = ERROR;
free(z);
free(y);
free(x);
}
return ret;
}
No comments:
Post a Comment