01-29-2007 08:29 AM
01-29-2007 09:18 AM
One way to avoid the problem of calloc/free within your function is to reserve the memory at the main() level of your code, either by a single calloc() at the beginning and free() at the end, or even by creating a static array with: char string2 [100]; at the outermost level of your program. This way your function could just access string2 directly.
Not the most elegant solution and not suitable for multi-threaded operation, but it should be good enough for simple programs, as long as you know the maximum array size beforehand.
JR
01-29-2007 10:03 AM
I am not sure that your suggestions will fix my question:
1. If I calloc/free memory at the main() level ... how it affects my function? You meant str_src or str_ret?
2. If I declare char string2 [100] in my fuction then I can not return string2 in my function
Can you specific more detail? Thanks
01-29-2007 10:42 AM
It is difficult to give more detail as it depends on the construction and intention of your overall program, and what you want to do with the returned string pointers. If you call your function several times and plan to store or compare the returned values then I agree that the approach I outlined will not work. If you just call it once and process the result before calling it again then it might be suitable. I can't tell without more information.
You are right it is not a good idea to return a pointer to a local automatic variable from a function - since these variables are allocated on the stack they turn to garbage as soon as the function returns. You can return an array that is statically declared inside the function, but then we could run into the first problem again.
Can you give us some idea of how you call this function - this could lead to different suggestions.
JR
01-29-2007 11:33 AM
01-29-2007 12:00 PM
Here how I try to do:
char *string_return(char *str_src)
{
char * strRet;
str_ret = calloc(1000, sizeof(char));
strcpy (str_ret, str_src);
void main (void)
{
char *str_send, *str_feedback;
str_send = "Does it work?"; // this string will be kept throughout the program = unchange!
str_feedback = string_return(str_send);
printf(str_feedback);
}
Note: I would like to have the same result without free (str_ret) and to have the str_feedback as: "Does it work? Yes, it does ..." without affecting content of str_send!
I hope that you now have more clear pucture about my question!
01-29-2007 12:10 PM
01-29-2007 01:03 PM
01-29-2007 02:27 PM