Search code examples
cstringstrdup

when strdup function fails?


i have following code which use strdup function

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

char source[] = "The Source String ";

int main()
{
  char *dest;
  if ((dest = _strdup(source)) == NULL)
  {
    fprintf(stderr, " Error allocation memory. ");
    exit(1);
  }
  printf("The destination = %s\n", dest);
  return 0;
}

it successfully says The Source String,but i am interesting in which situation it fails and how good it is usage of it in daily problems?i know that strdup it is determined by

char *strdup (const char *s)
{
    char *d = malloc (strlen (s) + 1);   // Space for length plus nul
    if (d == NULL) return NULL;          // No memory
    strcpy (d,s);                        // Copy the characters
    return d;                            // Return the new string
}

if our string is not NULL,is there any chance of failing strdup function?


Solution

  • Yes, if malloc fails to allocate memory and returns NULL.

    This could reasonably happen when you're trying to duplicate a very large string, or if your address space is very fragmented and nearly full (so taht malloc can't find a contiguous block of memory to allocate, or in embedded systems where not much memory is available.