[H-GEN] malloc() causing a segfault
Martin Pool
mbp at linuxcare.com.au
Thu Aug 31 00:23:14 EDT 2000
On Thu, Aug 31, 2000 at 02:03:46PM +1000, Andrae Muys wrote:
> [ Humbug *General* list - semi-serious discussions about Humbug and ]
> [ Unix-related topics. Please observe the list's charter. ]
>
> On Thu, 31 Aug 2000, Nikolai Lusan wrote:
>
> > basically it strips lead spaces from a line of text, yes I know is clumsy but
> > part of it was getting me back to pointers :)
> >
> Can't see anything wrong with the function itself (except that it's very
> clumsy). So the memory corruption will be outside the function.
>
> A better implementation would be to to the stripping in place and dodge
> the two copies, and leave it more idiomatic and easier to read.
Dude, an even better implementation would *work*. :-)
--
Martin Pool http://linuxcare.com.au/rproxy/
rproxy accelerates HTTP by dynamic caching and differential update
---------------------------
/* -*- compile-command: "make strip && ./strip \' Hello there world ! \'" -*- */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void stripLeadingSpacesInPlace(char *str) {
char *in, *out;
in = str;
out = str;
while (*in) {
if (!isspace(*in)) {
*out++ = *in++;
} else {
in++;
}
}
*out = '\0';
}
/* Strip leading spaces in place *correctly* */
void strltrim(char *s) {
char *p;
for (p = s; *p && isspace(*p); p++)
;
strcpy(s, p); /* C is very nice sometimes */
}
int main(int argc, char **argv) {
char *d1, *d2;
d1 = strdup(argv[1]);
stripLeadingSpacesInPlace(d1);
puts(d1);
d2 = strdup(argv[1]);
strltrim(d2);
puts(d2);
}
--------------------------
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
URL: <http://lists.humbug.org.au/pipermail/general/attachments/20000831/f5a1910e/attachment.sig>
More information about the General
mailing list