I am working on a Python C project that involves a couple of dynamically allocated structures like queues and threading structures. I am mainly looking to improve the readability. It looks something like this:
typedef struct Queue;
typedef struct Control;
typedef struct Logging;
typedef struct Args;
void cleanupQueue(Queue *q);
void cleanupControl(Control *c);
void cleanupLogging(Logging *l);
void cleanupArgs(Args *a);
PyObject *main(){
Queue *queue = (Queue *) malloc(sizeof(Queue));
if(!queue){
PyErr_SetString(type, message);
return NULL;
}
// initialize queue and fill
Control *control = (Control *) malloc(sizeof(Control));
if(!control){
cleanupQueue(queue);
PyErr_SetString(type, message);
return NULL;
}
// initialize control
Logging *logging = (Logging *) malloc(sizeof(Logging));
if(!logging){
cleanupControl(control);
cleanupQueue(queue);
PyErr_SetString(type, message);
return NULL;
}
// initialize logging
Args *args = (Args *) malloc(sizeof(Args));
if(!logging){
cleanupLogging(logging);
cleanupControl(control);
cleanupQueue(queue);
PyErr_SetString(type, message);
return NULL;
}
// initialize and fill args with the other structs
// Note: I guess I could check if they all exist before doing work with them here but I was unsure if that is a good practice since I am loading them into the args and am keen on getting the correct error message.
// bunch of work here
cleanupQueue(queue);
cleanupControl(control);
cleanupLogging(logging);
cleanupArgs(args);
return obj;
}
Now this code works just fine as long as it cleans up the allocated memory properly; although it lowers the flow of the code and its overall readability by a small margin, I am still looking to improve my structuring practices by any margin. I left a note in there marking that I could check each of the structures before doing any work(having all of the checking in the same place), but I feel as if this would result in the same flow.
Is there any way to do this in a way that ensures that I return the correct error while improving the structure of my code?