我的 c 字符串复制函数正在损坏其他变量的堆栈

My c-string copy function is corrupting the stack of other variables

本文关键字:其他 损坏 变量 堆栈 字符串 复制 函数 我的      更新时间:2023-10-16

这个函数在另一个程序中工作正常,但在某些情况下,它会导致运行时错误,指出某个变量周围的堆栈,有时甚至没有发送到函数中,被破坏了。

char *strCpy(char *dest, const char *source) {      // copy cstring
char *origin = dest;                            // non iterated address
while (*source || *dest) {
*dest = *source;
dest++;
source++;
}
return origin;
}

函数的实现:

int main() {
std::cout << "Will it crash?n";
char temp[255];
char b[255];
std::cin >> temp;
strCpy(b, temp);
std::cout << b;
std::cout << "endn";
return 0;
}

在这种情况下,temp 已损坏,但不一定是因为它已传递到函数中。除此之外,我很难找到这个问题。

我编写自己的复制函数的原因是因为项目的限制。我也不允许使用[]来索引数组

循环条件中的逻辑有缺陷,将导致未定义的行为

目标的内容未初始化,因此不确定。您根本不应该检查您的状况下的目的地,只检查来源:

while (*source) { ... }

当然,您需要将终止符添加到目的地。这可以简单地在循环后完成,例如

*dest = '';
相关文章: