Mailing List Archive

why C's string management sucks
/*
* "Re: votes" by Brian Behlendorf <brian@wired.com>
* written Sun, 9 Apr 1995 19:09:22 -0800 (PST)
*

> Something like (in psuedo-code)

> /* somewhere in a header file */
> char URL_string_stack[MAX_STRING_LENGTH];
> char *URL_string = URL_string_stack
> int using_URL_string_heap;

> /* in the body of the code */
> if (size_of_resource_required > MAX_STRING_LENGTH) {
> URL_string = (char *)malloc(size_of_resource_required);
> using_URL_string_heap = 1;
> }
> (do whatever you need to do)

> if (using_URL_string_heap) {
> free(URL_string);
> using_URL_string_heap = 0;
> }
> URL_string = URL_string_stack;

* Free()ing it should make sure it doesn't leak in rst's no-forking
* model.
*/

You could do that, but if you're going to do that why not use malloc()
to begin with? With the setup above, you have to keep track of three
separate variables for every string. You'd be better off using
malloc() and then realloc() later when you need more space.

The advantage of using local vars on the stack is that in a simpler
context, it's easier to manage. When the project started two years
ago, that decision made sense. As things got more and more complex it
made less and less sense.

--Rob