user466534
user466534

Reputation:

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?

Upvotes: 0

Views: 4483

Answers (3)

Alex
Alex

Reputation: 1232

It's not unheard of to run out of memory, if there is a memory leak. So it's not a bad idea to check for null, print out error message, and maybe even exit at that point. Note that things like 'printf' won't work (or may not work, but in my experience don't work) if you run out of memory. So you gotta use low-level 'write' or such, and file descriptor you're using (if you're writing to log file), should already be opened.

Upvotes: 1

Joey
Joey

Reputation: 354694

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.

Upvotes: 4

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43538

The chance of strdup failing is determined by the chance of malloc failing. On modern operating systems with virtual memory, a malloc failure is a very rare thing. The OS may have even killed your entire process before the system gets so low on memory that malloc has to return NULL.

Upvotes: 1

Related Questions