[英]My c-string copy function is corrupting the stack of other variables
This function worked fine in another program, but in some cases it causes a runtime error saying that the stack around some variable, sometimes one that wasn't even sent into the function, was corrupted. 该函数在另一个程序中可以正常工作,但是在某些情况下,它会导致运行时错误,表明某个变量(有时甚至没有发送到函数中)周围的堆栈已损坏。
char *strCpy(char *dest, const char *source) { // copy cstring
char *origin = dest; // non iterated address
while (*source || *dest) {
*dest = *source;
dest++;
source++;
}
return origin;
}
implementation of the function: 功能的实现:
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 << "end\n";
return 0;
}
In this case, temp is corrupted, but not necessarily because it was passed into the function. 在这种情况下,temp已损坏,但不一定是因为它已传递到函数中。 I'm having trouble hunting down the issue beyond this.
除此以外,我很难找到问题所在。
The reason I wrote my own copy function is because of restrictions on the project. 我编写自己的复制功能的原因是由于对该项目的限制。 I am also not allowed to use
[]
to index arrays 我也不允许使用
[]
索引数组
Your logic in the loop condition is flawed and will lead to undefined behavior . 您在循环条件下的逻辑有缺陷,并会导致不确定的行为 。
The contents of the destination is uninitialized and therefore indeterminate . 目的地的内容尚未初始化 ,因此不确定 。 You should not check the destination at all in your condition, only the source:
您不应该在所有情况下仅检查源:
while (*source) { ... }
And of course, you need to add the terminator to the destination. 当然,您需要将终止符添加到目标。 This can simply be done after the loop like
这可以简单地在循环之后完成,例如
*dest = '\0';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.