[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Groff] Readable tbl-source
From: |
Werner LEMBERG |
Subject: |
Re: [Groff] Readable tbl-source |
Date: |
Sun, 08 Sep 2002 20:47:26 +0200 (CEST) |
> 1 char *string::extract() const
> 2 {
> 3 char *p = ptr;
> 4 int n = len;
> 5 int nnuls = 0;
> 6 int i;
> 7 for (i = 0; i < n; i++)
> 8 if (p[i] == '\0')
> 9 nnuls++;
> 10 char *q = new char[n + 1 - nnuls];
> 11 char *r = q;
> 12 for (i = 0; i < n; i++)
> 13 if (p[i] != '\0')
> 14 *r++ = p[i];
> 15 q[n] = '\0';
> 16 return q;
> 17 }
>
> Does `new char[n]' give memory pre-filled with '\0'? I guess not
> because #15 puts the terminating '\0' in place. But if on entry ptr ==
> "a\0c\0" and len == 3
No. len == 4 for "a\0b\0". In a `string' class, strings aren't
null-terminated; if there is a trailing \0, it is part of the string.
> [...]
>
> Assuming I'm right that then...
>
> 19 void string::remove_spaces()
> 20 {
> 21 int l = len - 1;
> 22 while (l >= 0 && ptr[l] == ' ')
> 23 l--;
> 24 char *p = ptr;
> 25 if (l > 0)
> 26 while (*p == ' ') {
> 27 p++;
> 28 l--;
> 29 }
> 30 if (len - 1 != l) {
> 31 if (l >= 0) {
> 32 len = l + 1;
> 33 char *tmp = new char[len];
> 34 memcpy(tmp, p, len);
> 35 a_delete ptr;
> 36 ptr = tmp;
> 37 }
> 38 else {
> 39 len = 0;
> 40 if (ptr) {
> 41 a_delete ptr;
> 42 ptr = 0;
> 43 }
> 44 }
> 45 }
> 46 }
>
> given ptr == "abc \0" and len == 4 by #33 len == 3 and #34 will copy
> "abc" without a '\0' character on the end.
During the parsing of tbl items, no \0 is appended; remove_spaces will
see "abc " (with len == 4), converting it to "abc".
> The two routines don't seem to match in terms of what ptr holds, a
> \0 terminated string or not.
A trailing \0 must be explicitly inserted if necessary.
Werner