Thursday, October 24, 2013

What is strdup string function in C Language?

strdup string library function is used to create the duplicate string. It will do the following three steps.

  • It creates the dynamic memory (no need to use malloc/calloc)
  • It copies the content to the newly allocated memory 
  • It returns the allocated memory starting address
When we are using strdup function, we need use the free() function do deallocate memory which is allocated by strdup function, other we will get into the memory leak. Check the below sample code.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ONE_INT 1
void display()
{
     int local_a = 7;
     int *local_p = (int *)malloc(ONE_INT);
     printf("local memory location is %p\n",&local_a);
     printf("memory location using malloc is %p\n",local_p);
}
int main()
{
   char str_a[] = "Hello World";
   char *str_p = strdup(str_a);
   printf("local meory location is %p\n",str_a);
   printf("strdup memory location is %p\n",str_p);
   display();
}
OutPut:
local meory location is 0x7fff54cc0ba8
strdup memory location is 0x7fd0904000e0
local memory location is 0x7fff54cc0b7c
memory location using malloc is 0x7fd0904038a0

We can clearly observe that red colour address is from heap and blue colour address is from Stack. 

No comments:

Popular Posts