0

Consider I have a string called "bhuvanesh" , to store that string , Initially allocate the memory using malloc()

   char *ptr=(char *)malloc(sizeof("bhuvanesh"));
   sprintf(ptr,"bhuvanesh");

Then I want to add the string with the previously stored memory , the string is "waran". so I am using realloc()

 ptr=(char *)realloc(ptr,15);

The function realloc() will return the starting address, so concatenate the string I can use strcat() function

  strcat(ptr,"waran");

or else I can do like that

    char *p=ptr;
    p=p+sizeof("bhuvanesh");

    sprintf(p,"waran\n");

Is there is any way to do this ?

RedX
  • 14,749
  • 1
  • 53
  • 76
Bhuvanesh
  • 1,269
  • 1
  • 15
  • 25

2 Answers2

0

This is correct:

  strcat(ptr,"waran");

This is faulty:

    char *p=ptr;
    p=p+sizeof("bhuvanesh");

    sprintf(p,"waran\n");

p=p+sizeof("bhuvanesh") results in p pointing after the string-terminating '\0'; correct would be

    p += sizeof"bhuvanesh" - 1;

or

    p += strlen(p);

Plus sprintf(p,"waran\n") adds 6 bytes to the string, but you have only reallocated 5 more, so either

 ptr = realloc(ptr, 16);

or dropping the '\n', e. g.

    strcpy(p, "waran");

would be appropriate.

Armali
  • 18,255
  • 14
  • 57
  • 171
0

Leave the headache to the OS; not with you; I mean don't use strlen, strcpy and using + to find the exact locations; Now with this below approach you are done with what you want; Keep it simply stylish (KISS)

#include <stdio.h>
#include <malloc.h>
int main() 
{
    char *ptr = (char *) malloc(sizeof("bhuvanesh"));
    sprintf(ptr, "bhuvanesh");

    ptr = (char *)realloc(ptr, 15);

    sprintf(ptr, "%swaran", ptr);
    printf("%s\n", ptr);
    return 0;
}
Viswesn
  • 4,674
  • 2
  • 28
  • 45