0

I am trying to make a function like strcpy in C++. I cannot use built-in string.h functions because of restriction by our instructor. I have made the following function:

    int strlen (char* string)
{
    int len = 0;
    while (string [len] != (char)0) len ++;
    return len;
}

char* strcpy (char* *string1, char* string2)
{
    for (int i = 0; i<strlen (string2); i++) *string1[i] = string2[i];
    return *string1;
}
main()
{
       char* i = "Farid";
       strcpy (&i, "ABC ");
       cout<<i;
}

But I am unable to set *string1 [i] value. When I try to do so an error appears on screen 'Program has encountered a problem and need to close'.

What should I do to resolve this problem?

3
  • i will be in the read only part of the memory and therefore will have a problem. Use char[] i = "Farid"; instead Commented Dec 11, 2013 at 22:11
  • You sure this is a C++, not C class? Commented Dec 11, 2013 at 22:12
  • @LuchianGrigore - C is a classless society ;-) Commented Dec 11, 2013 at 22:14

4 Answers 4

3

Your strcpy function is wrong. When you write *string1[i] you are actually modifying the first character of the i-th element of an imaginary array of strings. That memory location does not exist and your program segfaults.

Do this instead:

char* strcpy (char* string1, char* string2)
{
    for (int i = 0; i<strlen (string2); i++) string1[i] = string2[i];
    return string1;
}

If you pass a char* the characters are already modifiable. Note It is responsibility of the caller to allocate the memory to hold the copy. And the declaration:

char* i = "Farid";

is not a valid allocation, because the i pointer will likely point to read-only memory. Do instead:

char i[100] = "Farid";

Now i holds 100 chars of local memory, plenty of room for your copy:

strcpy(i, "ABC ");

If you wanted this function to allocate memory, then you should create another one, say strdup():

char* strdup (char* string)
{
    size_t len = strlen(string);
    char *n = malloc(len);
    if (!n)
        return 0;
    strcpy(n, string);
    return n;
}

Now, with this function the caller has the responsibility to free the memory:

char *i = strdup("ABC ");
//use i
free(i);
Sign up to request clarification or add additional context in comments.

Comments

0

Because this error in the declaration of strcpy: "char* *string1"

I don't think you meant string1 to be a pointer to a pointer to char.

Removing one of the * should word

Comments

0

The code has several issues:

  1. You can't assign a string literal to char* because the string literal has type char const[N] (for a suitable value of N) which converts to char const* but not to char*. In C++03 it was possible to convert to char* for backward compatibility but this rule is now gone. That is, your i needs to be declared char const*. As implemented above, your code tries to write read-only memory which will have undesirable effects.
  2. The declaration of std::strcpy() takes a char* and a char const*: for the first pointer you need to provide sufficient space to hold a string of the second argument. Since this is error-prone it is a bad idea to use strcpy() in the first place! Instead, you want to replicate std::strncpy() which takes as third argument the length of the first buffer (actually, I'm never sure if std::strncpy() guarantees zero termination or not; you definitely also want to guarantee zero termination).
  3. It is a bad idea to use strlen() in the loop condition as the function needs to be evaluated for each iteration of the loop, effectively changing the complexity of strlen() from linear (O(N)) to quadratic (O(N2)). Quadratic complexity is very bad. Copying a string of 1000 characters takes 1000000 operations. If you want to try out the effect, copy a string with 1000000 characters using a linear and a quadratic algorithm.
  4. Your strcpy() doesn't add a null-terminator.
  5. In C++ (and in C since ~1990) the implicit int rule doesn't apply. That is, you really need to write int in front of main().

Comments

0

OK, a couple of things:

  1. you are missing the return type for the main function declaration. Not really allowed under the standard. Some compilers will still allow it, but others will fail on the compile.
  2. the way you have your for loop structured in strcpy you are calling your strlen function each time through the loop, and it is having to re-count the characters in the source string. Not a big deal with a string like "ABC " but as strings get longer.... Better to save the value of the result into a variable and use that in the for loop
  3. Because of the way that you are declaring i in `main' you are pointing to read-only storage, and will be causing an access violation

Look at the other answers here for how to rebuild your code.

Pointer use in C and C++ is a perennial issue. I'd like to suggest the following tutorial from Paul DiLorenzo, "Learning C++ Pointers for REAL dummies.".

(This is not to imply that you are a "dummy," it's just a reference to the ",insert subject here> for Dummies" lines of books. I would not be surprised that the insertion of "REAL" is to forestall lawsuits over trademarked titles)

It is an excellent tutorial.

Hope it helps.

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.