Search code examples
cfunctionpointersassertstrcpy

problem with strcpy() when trying to copy a string to a string


Recently started to do some c programming again and are currently having issues with an assignment. The following function are supposed to initialize a string by allocating memory for it, it is also the first assignment that I'm required to use Assert(). I have to write the funcion that dstring_initialize soo that the following works:

    DString str1, str2;

    str1 = dstring_initialize("");
    dstring_delete(&str1);
    assert(str1 == NULL);

It is probbly something basic that I have messed up and this is what the function looks like currently:

DString dstring_initialize(const char* str)
{
    assert(str != NULL);

    char* str1;

    str1 = (char*)malloc(sizeof(char));
    
    strcpy(str1, str);

    assert(str1 == str);

    return str1;
}

The error message I get is that the last Assert, Assert(str1 == str) fails and I've been trying different things but cant figure out what I've done wrong.


Solution

  • You have several fundamental misconceptions. First of all, there is no string class in C. There are just character arrays that could be used as strings if you append a null terminator \0 at the end of the array.

    • DString Hiding pointers char* behind typedef is incredibly bad practice. You'll only end up fooling yourself that you have some manner of string class when you don't. Get rid of this evil typedef.
    • str1 = (char*)malloc(sizeof(char)); This only allocates a single character, not very helpful.
    • strcpy(str1, str); This will copy until strcpy finds the null terminator in str. Which it does immediately since you passed "". So it will actually not copy anything other than the null terminator. It's essentially the same thing as str1[0]='\0';.
    • assert(str1 == str); compares addresses not contents. str1 and str are different objects and they will never have the same address, so this assert will always fail. To compare string contents, use strcmp().

    From here on I'd recommend to re-visit your C book and study arrays, pointers and strings, in that order.