Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Vec *vec_new() {
    Vec * new_struct = malloc(sizeof(struct Vec));
    if (new_struct != NULL){
        new_struct -> data = malloc(sizeof(int));
        if(new_struct -> data == NULL){
            free(new_struct);
            return false;
        }
        new_struct -> length =  0;
        new_struct -> capacity = 1;

    }else{
        free(new_struct);
    }
    return new_struct;
}


What I have tried:

......................................
Posted
Updated 30-May-21 13:24pm
Comments
[no name] 30-May-21 17:40pm    
How can you free and return false in the one case and not the other?
Graham Wilson 30-May-21 19:44pm    
Minor issue: the "return false" should be "return NULL"
as the function returns a pointer, not a bool(ean).
Dave Kreskowiak 30-May-21 20:44pm    
Why would you want to "optimize" this? With the corrections that have already been covered, there's really nothing to "optimize". The code works, is pretty easy to understand, and supportable.

About the only thing I would change is add comments.

1 solution

I would try
C++
Vec *vec_new() {
    Vec * new_struct = malloc(sizeof(struct Vec));
    if (new_struct != NULL){
        new_struct -> data = malloc(sizeof(int));
        if(new_struct -> data == NULL){
            free(new_struct);
            return false;
        }
        new_struct -> length =  0;
        new_struct -> capacity = 1;

    }else{
        // at this place, new_struct is NULL, which means that the malloc failed
        // so there is nothing to free
        free(new_struct);
    }
    return new_struct;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900