memcpy 问题;复制错误的块并多次
#include <iostream>
#include <string.h>
using namespace std;
int sk00(char * a) //use to find length, in characters, of an expression
{
int b = 1, c = 0;
while(b != 0)
{
if (a[c] == '`'){b++;}
else{b--;}
c++;
}
return c;
}
void sk07(char * a)
{
int b = 0; while(a[b]!=0){b++;}b -= 2;
memcpy(a,a+3,b);
memcpy(a+sk00(a),a+sk00(a)+sk00(a+sk00(a)),b);
}
void sk20(char * z)
{
char * a = z + 2;
int b = 0;while(a[b]!=0){b++;}b-=1;
memcpy(a,a+2,b);
int al = sk00(a), bl = sk00(a+al), cl = sk00(a+al+bl);
b=b-(al+bl+cl);
memcpy(a+al+cl+1, a+al, b+cl+bl);
}
int main()
{
char a[] = "``````s`k`sikabcd";
sk20(a+3);
cout << a << "; Final.\n";
}
终端输出:
pup@aurora-217:~/sk$ g++ sk5.c
pup@aurora-217:~/sk$ ./a.out
``````k`sikakakad; Final.
pup@aurora-217:~/sk$
我期待类似的输出
`````k
sik`sikabcd
#include <iostream>
#include <string.h>
using namespace std;
int sk00(char * a) //use to find length, in characters, of an expression
{
int b = 1, c = 0;
while(b != 0)
{
if (a[c] == '`'){b++;}
else{b--;}
c++;
}
return c;
}
void sk07(char * a)
{
int b = 0; while(a[b]!=0){b++;}b -= 2;
memcpy(a,a+3,b);
memcpy(a+sk00(a),a+sk00(a)+sk00(a+sk00(a)),b);
}
void sk20(char * z)
{
char * a = z + 2;
int b = 0;while(a[b]!=0){b++;}b-=1;
memcpy(a,a+2,b);
int al = sk00(a), bl = sk00(a+al), cl = sk00(a+al+bl);
b=b-(al+bl+cl);
memcpy(a+al+cl+1, a+al, b+cl+bl);
}
int main()
{
char a[] = "``````s`k`sikabcd";
sk20(a+3);
cout << a << "; Final.\n";
}
Terminal Output:
pup@aurora-217:~/sk$ g++ sk5.c
pup@aurora-217:~/sk$ ./a.out
``````k`sikakakad; Final.
pup@aurora-217:~/sk$
I'm expecting an output along the lines of
`````k
sik`sikabcd
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从技术上讲,如果 b 大于 2 或 3,则 sk07 会出现问题,因为在源和目标重叠的情况下无法使用 memcpy。你可以尝试 memmove 来代替。
例如,我们在这里是否有重叠
就很难说。
Technically you have a problem in sk07 if and when b is larger than 2 or 3, as you cannot use memcpy for cases where the source and target overlaps. You could try memmove instead.
Whether we have an overlap here, for example
is very hard to tell.
在内存位置可能重叠的情况下(代码中看起来就是这种情况),您应该使用 memmove 函数而不是 memcpy 例程。在内存位置重叠的情况下,memcpy 例程被认为不安全,因为优化可能会使结果输出变得一团糟。
memmove 采用与 memcpy 相同的顺序的相同参数,因此可以用作替代品。
In the case of potentially overlapping memory locations, which it looks like is the case in your code you should use the memmove function rather than the memcpy routine. The memcpy routine is considered unsafe to use in the case of overlapping memory locations and because of optimizations can make a complete mess of the resulting output.
memmove takes the same parameters in the same order as memcpy and so can just be used as a drop in replacement.