char * func(char * str)
{
char *ptr = (char *)malloc(strlen(str));
sprintf(ptr,"%s",str);
* (ptr +1) = 'E';
printf("%s\n",ptr);
return ptr;
}
void main()
{
char * str = "kundan";
char * str1 = func(str);
printf("%s\n",str1);
free(str1);
printf("%s\n",str1);
}
This is a very basic question but I am confused. I am sending a char * to a function and receiving a return value which is also char *. I cannot use stack memory in func() for the return as it will expire as soon func call is over. So , I am allocating memory in heap and returning it. Please suggest if there is better means and the memory which I am freeing in main is the right way of working.
Never use a pointer after you have given it to
free(), because the memory that the pointer pointed to is no longer available for you to read or write. Using a pointer after you have freed it results in undefined behaviour. In your case, it may print the string again, or it may crash.Also, don’t forget, that strings in C require an extra
charto hold the'\0'character (terminating null character).The length of the string is 6, but it occupies 7
charin memory, so when you callmallocand only give it the length of the string, you won’t have enough space for the the null character. Again, the operating system might give you extra anyway and it may be working in this case for you, but never rely on this, you must only use the number of bytes that you asked for.