memcpy问题;复制错误的块和多次

memcpy issues; copying wrong block and multiple times

本文关键字:错误 问题 复制 memcpy      更新时间:2023-10-16
#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$ 

我期望输出沿着

`````ksik`sikabcd

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

memcpy(a+al+cl+1, a+al, b+cl+bl); 
的行

在可能存在内存位置重叠的情况下,您应该使用memmove函数而不是memcpy例程。在内存位置重叠的情况下,使用memcpy例程被认为是不安全的,因为优化可能会使结果输出完全混乱。

memmove接受与memcpy相同的形参,顺序相同,因此可以用作替换符