Wednesday, October 2, 2013

c/c++: the good old returning local variable

 

http://stackoverflow.com/questions/423186/since-i-cant-return-a-local-variable-whats-the-best-way-to-return-a-string-fr

From what I've seen, this should work as expected:

void greet(){
char c[] = "Hello";
greetWith(c);
return;
}

but this will cause undefined behavior:

char *greet(){ 
char c[] = "Hello";
return c;
}
 
 

You're absolutely right. Your c array in the second example is being allocated on the stack, and thus the memory will get reused immediately following. In particular, if you had code like

 printf("%s\n",greet());

you'd get weird results, because the call to printf would have reused some of the space of your array.

The solution is to allocate the memory somewhere else. For expample:

char c[] = "Hello";

char * greet() {
return c;
}

Would work. Another choice would be to allocate it statically in scope:

char * greet() {
static char c[] = "Hello";
return c;
}

because static memory is allocated separately from the stack in data space.

Your third choice is to allocate it on the heap via malloc:

char * greet() {
char * c = (char *) malloc(strlen("Hello")+1); /* +1 for the null */
strcpy(c, "Hello");
return c;
}

but now you have to make sure that memory is freed somehow, or else you have a memory leak.

No comments:

Post a Comment