Clunky C cleanup code

P

Paul Hsieh

fatted said:
I've written a function (clean_string) to remove characters from a string,
but it looks clunky to me, and I'm sure there's a more 'C' like way of
doing it (still learning), comments and advice welcome...

This code is bug central.

1. You have a potential Buffer overflow in your declaration of mod[].
Basically, if "string" is long enough, then size_start can become
large enough (say, more than 6 characters) so that your
"%.<size_start>s%s" construction is not going to fit.

2. Follow the assignments of final and string in your inner loop.
What you are doing is you are calling realloc on final and storing
back to final, then writing to final with sprintf using string as one
of the sources, then aliasing string to final, then repeating. The
problem is that asymptotically, string becomes undefined after you
assign final with realloc, so you can't properly use it as a source
for final through sprintf.

3. Even if you knew that the realloc never moved the pointer
(presumably since it always decreases), string is aliased to final, so
using it as a source argument for a sprintf that writes to final is
not defined.

4. malloc can fail and return NULL. So the strcpy(final, string);
line might immediately crash.

I would recommend that you simply perform direct scanning for
"choppable spans" and use the "memmove()" library function to pack
together the inverse spans. For an example of this see the breplace()
and bfindreplace() functions in "The Better String Library" which can
be downloaded from http://bstring.sf.net/ . Or you could just use the
better string library directly (just call bfindreplace on each
character that you intend to chop as a singleton string replaced with
"".)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,404
Latest member
PerryRutt

Latest Threads

Top