Say, I have code like this:
int foo() {
...
int buff_size;
scanf("%d", &buff_size);
FILE * fp = fopen("./file", "a+");
char *buff = malloc(buff_size*sizeof(char));
char *buff2 = malloc(buff_size*sizeof(char));
char *buff3 = malloc(buff_size*sizeof(char));
while (!feof(fp)) {
/*do something, say read, write etc.*/
if (/*error case 1*/) {
free(buff);
free(buff1);
free(buff3);
fclose(fp);
return -1;
}
else if (/*error case 2*/) {
free(buff);
free(buff1);
free(buff3);
fclose(fp);
return -2;
}
...
else if (/*error case k*/) {
free(buff);
free(buff1);
free(buff3);
fclose(fp);
return -k;
}
}
...
free(buff);
free(buff1);
free(buff2);
fclose(fp);
return 0;
}
for C doesn't provide try...throw...finally syntax, I have to close file descriptors and free heap memories pointer that I created before I return a error integer code. It produces some duplicated code that makes the code ugly.
Do anyone know how should I modifly this kind of code to make it looks more brief?