Dint find the exact link to my answer, so asking this simple question in terms where the function returns the char *
I wrote the code in this way so that the concat function itself should allocate & free the memory.
Can anyone plz help with the questions:
1) Is the freeing of memory placed correctly? (I ran Valgrind & found no issues as well)
2) How come pointer "ptr" which is allocated holding value, as per my understanding, if a memory to a ptr is freed, then value also should be lost right? Kindly correct me if am wrong.
char * concat(char *str1, char *str2)
{
char *ptr;
ptr=(char*)malloc(strlen(str1)+strlen(str2)+1); //allocated+1 for NULL character as well
int i=0,j=0;
while(str1[i]!='\0')
{
ptr[j]=str1[i];
printf("letter from src is %c\n",str1[i]);
i++; j++;
}
i=0;
while(str2[i]!='\0')
{
ptr[j]=str2[i];
j++;i++;
}
ptr[j]='\0';
cout<<ptr;
free(ptr);
return ptr;
}
int main()
{
char *str1="hello";
char *str2="world";
cout<<str1<<endl;
cout<<str2<<endl;
char *res=concat(str1,str2);
return 0;
}