调试断言 使用指针时失败

Debug Assertion Failed when using pointer

本文关键字:失败 指针 断言 调试      更新时间:2023-10-16

我试图更好地理解指针,并且很难弄清楚为什么我的代码会导致调试断言失败。当我注释掉"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;