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;
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With