I tried to make my own strdup function to practice my C skills, but I'm not sure if it's legal or not.
the function is down below:
char*
strdup(char* str) {
char* dup_str;
int len;
for (len = 0; *str != '\0'; ++len) {
dup_str = str;
dup_str++;
str++;
}
dup_str -= len;
return dup_str;
}
I have tested it a bit, but I'm still not sure if it is legal. It may be completely incorrect, so I'm surprised that it works the way it does at the moment.
Ignoring the undefined behaviour that occurs for strings larger than
INT_MAXchars long, your code is equivalent to the following:This is completely wrong. For starters,
strdup's main purpose is to allocate a new string, yet your function allocates no memory.strdupcan be summarized into four steps:Fixed: (Added after OP made attempt to fix in the comments.)
We can also replace the other string functions.