aegis said:
That doesn't overlap. See
http://groups-beta.google.com/group/comp.std.c/msg/03a4a0c929fd2138?dmode=source
imagine that you have, "aabbccdd"
and you search for the substring "dd"
then p points to the first "d" and
p + strlen(sub) would point one past the
second "d". This means a distinct value of
an object is used to assign to another
distinct object. Overlap does not mean
any two pointers pointing in the same
memory region. It is an overlap when
the objects within the memory region
are not distinct. Consider this:
strcpy(p + 3, p); p overlaps p + 3 here
the converse cannot be said for p+offset
overlapping p.
No, there is an overlap problem. For strcpy(), the Standard does
not define in what order the characters from the string(arg 2)
are copied to the character array(arg1). Among possiblities,
an implementor may copy from the beginning of the string to the
end terminating character, as in function Mystrcpy1 example below.
Another possibility is for the implementor to copy to the character
array from the string's terminating character to the beginning of the
string, as shown in the function Mystrcpy2 example below.
Now, take the string "aabbccdd", and, attempt to remove the
substring "cc". It the implementor made strcpy like the Mystrcpy1
example, you will get away with using the strcpy. But, if the
the implementation was similiar to function Mystrcpy2 then the
resulting string will be wrong, "aabb" instead of "aabbdd".
Run the following to see the effect.
#include <stdio.h>
#include <string.h>
char *Mystrcpy1(char *s, const char *cs);
char *Mystrcpy2(char *s, const char *cs);
void func1(char *src, char *sub);
void func2(char *src, char *sub);
int main(void)
{
char s[32], *substr = "cc";
Mystrcpy2(s,"aabbccdd");
printf("From the string: \"%s\"\n",s);
printf("We will attempt to remove substring \"%s\"\n",substr);
func1(s,substr);
printf("Using function Mystrcpy1. The result: \"%s\"\n\n",s);
Mystrcpy2(s,"aabbccdd");
printf("From the string: \"%s\"\n",s);
printf("We will attempt to remove substring \"%s\"\n",substr);
func2(s,substr);
printf("Using function Mystrcpy2. The result: \"%s\"\n",s);
return 0;
}
char *Mystrcpy1(char *s, const char *cs)
{ /* Copy from beginning of string cs to the end */
char *s1;
const char *cs1;
for(s1 = s,cs1 = cs; '\0' != (*s1 = *cs1); s1++,cs1++) ;
return s;
}
char *Mystrcpy2(char *s, const char *cs)
{ /* Copy from the end of string cs to the beginning */
const char *tmp;
size_t n = strlen(cs);
for(tmp = cs+n; ; tmp--,n--)
{
*(s+n) = *tmp;
if(!n) break;
}
return s;
}
void func1(char *src, char *sub)
{ /* Using function Mystrcpy1 */
char *p;
if ((p=strstr(src,sub)) != NULL)
Mystrcpy1(p,p+strlen(sub));
return;
}
void func2(char *src, char *sub)
{ /* Using function Mystrcpy2 */
char *p;
if ((p=strstr(src,sub)) != NULL)
Mystrcpy2(p,p+strlen(sub));
return;
}