我的 c 字符串复制函数正在损坏其他变量的堆栈
My c-string copy function is corrupting the stack of other variables
这个函数在另一个程序中工作正常,但在某些情况下,它会导致运行时错误,指出某个变量周围的堆栈,有时甚至没有发送到函数中,被破坏了。
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 = ' ';
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 为什么会发生堆损坏
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在其他文件中创建类时在 c++ 项目中不起作用
- 平均图像时图像损坏
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 类与私有变量的其他类之间的线程安全性
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- GlobalAlloc而不是其他分配方法
- 我的 c 字符串复制函数正在损坏其他变量的堆栈
- 尝试读取或写入受保护的内存.这通常表示其他内存已损坏.在C++Dll中
- 已尝试读取或写入受保护的内存.这通常表示其他内存已损坏 DllImport
- C++.NET包装程序:试图读取或写入受保护的内存.这通常表示其他内存已损坏
- 附加信息:试图读取或写入受保护的内存.这通常表明其他内存已损坏
- 堆损坏在VS中检测到错误,但在其他IDE中工作良好
- 试图读写受保护的内存.这通常表明其他内存已损坏