Create strdup in C

I am trying to write the following function in C,

char* modelstrdup(char* source);

The function should mimic the standard C library function strdup. The parameter is the string we want to duplicate. The returned pointer will point to the heap. When you write this function, create a structure stringon the heap that contains a copy of the source. Set the length and capacity of your string to the number of characters in the source. Be sure to return the address of the first character in the string, and not the address of the string string.

This is the only hint my professor gave me, but I don’t even know where to start ...

//Client Program Format only, will not work!
char* s; // should be "yo!" when we‟re done
String* new_string = malloc(sizeof(String) + 10 + 1);
(*new_string).length = 3; // 3 characters in "yo!"
(*new_string).capacity = 10; // malloced 10 bytes
(*new_string).signature = ~0xdeadbeef;
(*new_string).ptr[0] = „y‟;
(*new_string).ptr[1] = „o‟;
(*new_string).ptr[2] = „!‟;
(*new_string).ptr[3] = 0;
s = (*new_string).ptr;
printf("the string is %s\n", s);

Any suggestions? Thanks!

0
source share
1 answer

Here is a hint

char* strdup(char *str)
{
        char* ret = (char*)malloc(strlen(str)+1);

        //copy characters here
        return ret;
}
+4
source

Source: https://habr.com/ru/post/1721051/


All Articles