[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: So you think you are (or wanna be) a hacker



John Summerfield wrote:
Jason Rennie wrote:

On Thu, Aug 12, 2004 at 10:59:36AM +0800, John Summerfield wrote:
So set the ball rolling, here is a snippet from a program I found via freshmeat the other day:
    configfile = malloc(strlen(getenv("HOME")) + 20);
    sprintf(configfile,"%s/%s",getenv("HOME"), cfgfile);


Something a bit safer...

char *home = getenv("HOME");
if (home == NULL || cfgfile == NULL) hittheuseronthehead();
;-)

I like this because it's conservative and clearly coded. There are many short cuts in C which make more concise code. However, the most important code readers aren't compilers, they're people. When the code doesn't work as expected, it's people and not compilers who have to figure out what's wrong, and it's then that clear code becomes more important.

Often too, clear code won't have as many bugs in the first place, but then even bug-free code needs changes when requirements change.

int sz = strlen(home) + strlen(cfgfile) + 2;
char *configfile = malloc(sizeof(char)*sz);
sprintf(configfile,"%s/%s",home,cfgfile);

I'm sure someone can do better (and be more creative :)

On Wed, Aug 11, 2004 at 08:31:49PM -0700, Stefan Nicolai O'Rear wrote:
* It's very ugly (atleast to me.)


Is there such a thing as pretty C code?  Or C++ code for that matter?

:-)

I have some aprehensions about use of extensions as in Stefan's reply because they're non-standard and reduce portability.

Is there interest here in more of this kind of thing?

IMO for stuff like the above the c++ strings should be used (unless there is some reason to use pure C or you really need every bit of performance boost you can get), even in otherwise C source. There's number of C++ fueatures/libs that can be used withotu going fully OO and IMO using containers (STL) at least somewhat is a lot better that juggling pointers (except of special cases maybe).

	erik



Reply to: