#include #include #include #include typedef struct myString_t { int length; char *str; } * MyString; // Note that type MyString is a pointer type // takes a null terminated array of char as the argument MyString MyString_create(const char * cstring) { MyString result = malloc(sizeof(*result)); if ( result == NULL ) return NULL; if (cstring == NULL ) { result->length = 0; result->str = NULL; return result; } result->length = strlen(cstring); result->str = malloc(result->length); if ( result->str == NULL ) { free(result); return NULL; } memcpy(result->str, cstring, result->length); // don't copy '\0' return result; } // deep copy - takes another MyString as the argument // beware "MyString_copy(str, str);" bool MyString_copy(MyString dest, const MyString src) { if ( src == NULL || dest == NULL ) return false; // if malloc() fails here, we want dest to be unchanged char *strcopy = malloc(sizeof(char) * src->length); if ( strcopy == NULL ) return false; if ( dest->str != NULL ) free(dest->str); memcpy(strcopy, src->str, src->length); dest->str = strcopy; dest->length = src->length; return true; } void MyString_print(MyString s) { if ( s == NULL ) return; printf("(%d) ", s->length); for ( int i = 0; i < s->length; i++ ) { putchar(s->str[i]); } putchar('\n'); } int main(int argc, char *argv[]) { MyString myString = MyString_create("mystring"); MyString_print(myString); MyString yourString = MyString_create("yourstring"); MyString_print(yourString); if ( !MyString_copy(myString, yourString) ) exit(1); MyString_print(myString); // what does valgrind say about the exeution of this code? return EXIT_SUCCESS; }