user3690211
user3690211

Reputation: 21

Custom strcpy function not returning expected pointer

#include<stdio.h>
#include<stdlib.h>
char *str_cpy(char *, char *);
void main()
{
    char *desti= (char *)calloc(sizeof(char),10);
    char *m= (char *)calloc(sizeof(char),10);
    m = str_cpy(desti,"dhawal");
    printf("destination string is :%s\n",desti);
    printf("%s\n",m);

}

char *str_cpy(char *a,char *b)
{
    while(*b!='\0')
    {
        *a = *b;
        a++;
        b++;
    }
    *a = '\0';
    return a;
}

Please explain why m is not assigned with value of desti here?

It assigns a value to a third variable the result of string copy

Upvotes: 1

Views: 144

Answers (1)

Ed Heal
Ed Heal

Reputation: 60007

  1. You have a memory leak.
  2. desti will contain "dhawal"
  3. m will point to the null character of that string. That is the same value as a at the end of str_cpy

To avoid this use

char *str_cpy(char *a,char *b)
{
    char *r=a;
    while(*b!='\0')
    {
        *a = *b;
        a++;
        b++;
    }
    *a = '\0';
    return r;
}

Upvotes: 6

Related Questions