Hacker News new | past | comments | ask | show | jobs | submit login

a bit of optimization in $src/libsass/copy_c_str.cpp

        char* copy_c_str(const char* orig)
        {
                size_t len =  strlen(orig) + 1 ;             
                char* copy = (char*) malloc(sizeof(char) * len );
                memcpy(copy, orig, len);
                return copy;
        }



Uh, okay. I didn't read the original, sounds somewhat scary.

Anyway, please don't cast the return value of malloc() in C (http://stackoverflow.com/a/605858/28169).

Also, of course len should be const and sizeof (char) should be removed. Also testing whether malloc() succeeded before relying on the result being valid is a good idea (but perhaps there's machinery in place to abort on error), as is deciding what to do if the input string is NULL.


Anyway, please don't cast the return value of malloc() in C (http://stackoverflow.com/a/605858/28169).

It's C++.


Wouldn't this be even better:

    return( strdup( orig ) );

?


or maybe just #define copy_c_str strdup ?


Thanks, I'll give it a try and benchmark it. Also, pull requests are welcome for this sort of thing!


[deleted]


it will; he allocates and copies strlen()+1 bytes




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: