Buffer* b_create(int init_capacity, char inc_factor,char o_mode){
Buffer* buffer=NULL; /*local pointer to the buffer structure on heap*/
if (o_mode=='f' || inc_factor==0){
o_mode=0;
inc_factor=0;
}else if (o_mode=='f' && inc_factor!=0){
o_mode=0;
inc_factor=0;
}else if (o_mode=='a' && 1<=inc_factor<=255){
o_mode=1;
inc_factor=inc_factor;
}else if (o_mode=='m' && 1<=inc_factor<=100){
o_mode=-1;
inc_factor=inc_factor;
}
else{
buffer=NULL;
return buffer;
}
//throw a more meaningful error??
//cleanup :: how about i just call the ca_destroy() ??
/*
free(buffer->ca_head);
buffer->ca_head=NULL;
free(buffer);
buffer=NULL;
*/
buffer = (Buffer*)malloc(sizeof(Buffer));
buffer->ca_head=(char*)malloc(sizeof(char)*init_capacity);
buffer->mode=o_mode;
buffer->inc_factor=inc_factor;
buffer->capacity=init_capacity;
buffer->addc_offset=0;
buffer->mark_offset=0;
buffer->r_flag=0;
return buffer;
}
I have the above method. I am trying to get it to work. First of all, I check and set a couple of variables. If none of the cases apply, then I am setting the buffer to NULL and attempting to return the value to the calling function.
else{
buffer=NULL;
return buffer;
}
However after that return, the function continues and goes ahead and creates the buffer structure anyways. I was hoping that the function would exit once it sees a return statement. Why does it continue executing ??
This condition
is always true. It is parsed as
(1 <= inc_factor) <= 255, and1 <= inc_factorevaluates to either 0 or 1. So ifo_modeis one of'a'or'm', one of the earlier conditions holds, even ifinc_factoris 0 or negative.Looking at the condition-chain, we find:
but if
o_modeis none of'f', 'a', 'm'andinc_factor != 0, then the finalelseis reached andNULLis returned. There is no implementation broken enough to ignore areturnstatement.