muhm
muhm

Reputation: 1

Trying to copy a char* to another char*

I have a problem that my code

char* strdup(const char* s)
{
    int n = 0;

    for(; *s != 0; s++)
    {
        n++;
    }

    char* p = new char[n+1];

    for(int i = 0; i < n; i++)
    {
        p[i] = s[i];
    }
    p[n] = 0;

    return p;
}

int main()
{
    const char* p = "testing";

    char* p_copy = strdup(p);

    std::cout << p << '\n' << p_copy << std::endl;

    return 0;
}

doesn't work as intended.

I want to write a function which takes in const char* and copies it to a new allocated char memory. When it is done it should return a pointer to the char.

Now when I try it out my output is simply:

testing

thanks for any help in advance

Upvotes: 0

Views: 1097

Answers (2)

eerorika
eerorika

Reputation: 238371

Here:

for(; *s != 0; s++)

You increment s. So it no longer points to the beginning of the input string. It points to the null terminator of the string. Then, here:

for(int i = 0; i < n; i++)
{
    p[i] = s[i];

You try to copy n characters starting from the null terminator, and you end up reading past the end of the array which has undefined behaviour.

Solution: Make a copy of s for counting the characters:

const char* s2 = s;
for(; *s2 != 0; s2++)

Even better, you could refactor the length counting part into a reusable function called strlen.

Upvotes: 0

vacuumhead
vacuumhead

Reputation: 509

Try not incrementing s before you start copying it to p. I notice that in your first for loop you increment s until it points at a null, and then later use that pointer value to start your string copy. No wonder you are getting a null string.

Upvotes: 1

Related Questions