调试断言 使用指针时失败
Debug Assertion Failed when using pointer
我试图更好地理解指针,并且很难弄清楚为什么我的代码会导致调试断言失败。当我注释掉"while (*neu++ = *s++);"并在"strcopy(neu, s);"中注释时,它工作得很好。他们不应该这样做吗?
#include <iostream>
#include <cstring>
using namespace std;
void strcopy(char* ziel, const char* quelle)
{
while (*ziel++ = *quelle++);
}
char* strdupl(const char* s)
{
char *neu = new char[strlen(s) + 1];
while (*neu++ = *s++);
//strcopy(neu, s);
return neu;
}
int main()
{
const char *const original = "have fun";
cout << original << endl;
char *cpy = strdupl(original);
cout << cpy << endl;
delete[] cpy;
return 0;
}
strcopy
获取指针neu
的副本,因此当您返回字符串时neu
它仍然指向字符串的开头。使用 while 循环strdup1
您在返回之前修改neu
。在此指针上调用 delete
会导致失败,因为它与new
'd 的不同。
解决方案是使用临时变量递增和复制字符串。
char *neu = ...
char *tmp = neu;
while (*tmp++ = *s++);
return neu;
相关文章:
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 访问提升:shared_ptr 主范围外崩溃,断言失败:px != 0.指针的正确用法是什么?
- 函数返回时,带指针的复制构造函数失败
- 作为模板参数的成员函数指针在继承的成员函数上失败,如何以及为什么?
- 模板参数推导/替换失败,lambda作为函数指针
- C++ 调试断言失败,无效的空指针
- 对于实际指针类型,用于检测类似指针(可取消引用)类型的模板函数失败
- C++指向成员的指针的类内初始化会使 MSVC 失败(但 GCC/Clang 工作)
- SFINAE 序列化共享指针失败
- 如何在类中存储指向字符串到成员函数映射的智能指针,以便它不会因类型不完整而失败?
- 通过功能指针通过DLL进行回调功能,运行时检查失败#0错误
- 为什么指针到成员函数的模板参数推断失败
- Visual Studio 2010 调用 _locking() 失败 (errno = 22) 当文件指针高于 (2^
- C++ 调试断言失败指针
- 删除SDL_VideoInfo指针时调试断言失败
- 使用通搭指针时在给定位置执行失败的原因,而不是更早?
- SetFilePointer不会失败,但也不会移动指针
- 返回指向指针数组的指针获取下一个元素失败
- 尝试将值分配给*此指针失败
- 模板化的出列无效指针:删除类时失败