3

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

1 Answer 1

5

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.