Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cause of pointer error

Status
Not open for further replies.

aliad2002

Programmer
Jun 19, 2007
2
US
Hi
Dose anyone know why this code does not work?
char *foo() {
char string[32]; ...;
return string;
} is incorrect
but why?
 
string is a pointing to a local char array (on the stack), not to a dynamically allocated chunk of memory (on the heap). Things on the stack go bye-bye once they go out of scope (i.e. when the function ends). Things on the heap stay until you free that memory.
 
Thanks cp, now a fair question would be how can we fix this problem?
 
Pass the result string as a parameter, so the responsibility for allocating it is with the caller. Eg. strcpy()

Make the array static, so the function reserves a fixed sized array. Eg. asctime().
The disadvantage of this is calling the same function twice trashes the previous result.

Allocate the string inside the function and return the newly allocated memory. The non-standard strdup() would be an example.
The disadvantage is that the caller has to know it was allocated, and then free it at some point.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top