Imagine that I have this code, my question is if in the realloc_str()
function is it necessary to make an aux pointer so that I can free the content of the struct if the realloc
fails. Could it be done in main()
?
typedef enum { ERROR = 0, OK = 1 } STATUS;
typedef struct _str {
int *a;
} Str;
Str *new_str() {
Str *s = (Str *)malloc(sizeof(Str));
if (!s) {
return NULL;
}
s->a = (int *)malloc(sizeof(int) * 1);
if (!s->a) {
return NULL;
}
return s;
}
STATUS realloc_str(Str *s, int a) {
if (!s->a||!s) {
return ERROR;
}
//this is what I mean if it is necessary to make an aux pointer to make a control of errors
int *aux = s->a;
s->a = (int *)realloc(s->a,sizeof(int) * a);
if (!s->a) {
//could this free(aux) be done in main()?
//is this necessary?
free(aux);
return ERROR;
}
return OK;
}
int main() {
Str *s = new_str();
if (!s) {
free(s);
return ERROR;
}
if (realloc_str(s, 2) == ERROR) {
free(s);
return ERROR;
}
free(s);
free(s->a);
return 0;
}