CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Duplicating a string

We know that:

  • C considers null-byte terminated character arrays as strings, and
  • that the length of such strings is not determined by the array size, but by where the null-byte is.

So how could we take a duplicate copy, a clone, of a string? We could try:

#include <string.h>

char *my_strdup(char *str)
{
    char bigarray[SOME_HUGE_SIZE];

    strcpy(bigarray, str);  // WILL ENSURE THAT bigarray IS NULL-BYTE TERMINATED 

    return bigarray;        // RETURN THE ADDRESS OF bigarray
}

But we'd instantly have two problems:

  1. we'd never be able to know the largest array size required to copy the arbitrary string argument, and
  2. we can't return the address of any local variable. Once function my_strdup() returns, variable bigarray no longer exists, and so we can't provide the caller with its address.

 


CITS2002 Systems Programming, Lecture 12, p3, 29th August 2023.