CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Duplicating a string revisited

We'll now use malloc() to dynamically allocate, at runtime, exactly the correct amount of memory that we need.

When duplicating a string, we need enough new bytes to hold every character of the string, including a null-byte to terminate the string.
This is 1 more than the value returned by strlen:

#include <stdlib.h>
#include <string.h>

char *my_strdup2(char *str)
{
    char *new = malloc( strlen(str) + 1 );

    if(new != NULL) {
        strcpy(new, str);  // ENSURES THAT DUPLICATE WILL BE NUL-TERMINATED 
    }
    return new;
}

Of note:
  • we are not returning the address of a local variable from our function - we've solved both of our problems!

  • we're returning a pointer to some additional memory given to us by the operating system.

  • this memory does not "disappear" when the function returns, and so it's safe to provide this value (a pointer) to whoever called my_strdup2.

  • the new memory provided by the operating system resides in a reserved (large) memory region termed the heap. We never access the heap directly (we leave that to malloc()) and just use (correctly) the space returned by malloc().

 


CITS2002 Systems Programming, Lecture 12, p6, 28th August 2024.