Debug Assertion使用指针时失败

时间:2016-03-15 20:16:00

标签: c++ debugging pointers

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

1 个答案:

答案 0 :(得分:5)

strcopy获取指针neu的副本,因此当您返回时,neu仍然指向字符串的开头。在strdup1内部使用while循环,您在返回之前修改neu。在此指针上调用delete会导致失败,因为它与new'd不同。

解决方案是使用临时变量来增加和复制字符串。

char *neu = ...
char *tmp = neu;
while (*tmp++ = *s++);
return neu;
相关问题