Little-God
Little-God

Reputation: 233

Debug Assertion Failed when using pointer

I am trying to understand pointers a little better and have a hard time to figure out why my code causes a debug assertion failure. When i comment out "while (*neu++ = *s++);" and comment in "strcopy(neu, s);" it works just fine. Shouldn't they do the same?

#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;
}

Upvotes: 3

Views: 1133

Answers (1)

Kevin
Kevin

Reputation: 7324

strcopy takes a copy of the pointer neu, so neu still points to the beginning of the string when you return it. With the while loop inside of strdup1 you are modifying neu before you return it. Calling delete on this pointer causes the failure because it's different from what was new'd.

The solution is to use a temporary variable to increment and copy over the string.

char *neu = ...
char *tmp = neu;
while (*tmp++ = *s++);
return neu;

Upvotes: 5

Related Questions