If I want to return a pointer to a string created within a function, would this be correct:
Code:char * myfunc(){ char mystr[128]; return (mystr); }
If I want to return a pointer to a string created within a function, would this be correct:
Code:char * myfunc(){ char mystr[128]; return (mystr); }
Many junglists take pride in their belongin to what may be referred to as a globalised drum & bass subculture, as a subculture though, it is not nearly as distinct at gothic or punk!
Yes and no. It's correct in the way that it will compile, and the compiler will return the address of "mystr".
However, it is incorrect in the sense that the string will be "lost" and almost certainly overwriten once the function is left. This is because "mystr" is a local variable, and you are just passing the address back to the calling function. That address is only valid within the function, not after the function has been left (returned from).
There are three (suitable) options to do this:
1. Use a static local variable. This is a "global variable" but it's only visible within the function. This is not suitable if your application ever gets multi-threaded, and since you there is only ever ONE string there, if another call is made, the original value is changed. E.g:
2. Pass in a string as an argument to the function, and fill it in. Don't forget to pass along the length, so that the function can make sure it doesn't overwrite the end of the string.2. Pass in a string as an argument to the function, and fill it in. Don't forget to pass along the length, so that the function can make sure it doesn't overwrite the end of the string.Code:char *myfunc(const char *s) { static char local[100]; strncpy(local, s, sizeof(local)-1); return local; } int main() { char *a, *b; a = myfunc("abc"); b = myfunc("def"); printf("a=%s, b=%s\n", a, b); } // Output: a=def, b=def
3. Allocate memory using malloc - but you must then free it somewhere, or your application will leak memory and if it runs for a long enough time may expand to take up all the memory available in the machine.
--
Mats
Last edited by matsp; 08-31-2007 at 08:41 AM.
Hehe, classic job interview question. ;-)
Most sensible thing to do would be to pass in a char * and a length and let the function fill that char* to the given length.
If you don't want to impose a max length (and I've recently come across code, where the passed length made a huge difference to the way the function worked), the function will have to malloc memory. Normally, the function that mallocs memory is supposed to free it as well, but in this case you could make an exception. If a function returns a char *, you can be pretty sure that you will have to free the memory after you're done.
QuantumPete
"No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
"Have you tried turning it off and on again?" - The IT Crowd