What Does This Function Return ? (sometimes Same String, Sometimes Missing A Char)

- 1 answer

What does this code do exactly ? sometimes it returns same string and sometimes the string missing a char. why is that ?

char *string_dup(const char *s) {
    size_t n = strlen(s);
    char *t = malloc(n * sizeof(char));
    if (t == NULL) return t;
    for (unsigned int i = 0; i < n; ++i) 
        t[i] = s[i];
    t[n - 1] = '\0';
    return t;


What does this code do exactly ?


  • Accepts a pointer to a null terminated character string.
  • Allocates memory for a null terminated string that is shorter by 1 characters than the input string.
  • Copies the input string into the memory excluding the null terminator.
  • Writes null terminator over the last character.
  • Returns the pointer to the allocated memory that contains the copied substring.

P.S. Avoid using malloc in C++.

P.P.S. Avoid owning bare pointers in C++.

P.P.P.S. If the input string is empty, then the behaviour of the program is undefined. Makes sense since an empty string doesn't contain a strictly shorter substring.

P.P.P.P.S. * sizeof(char) is redundant because sizeof(char) is always 1.