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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Scope of local variables

Status
Not open for further replies.

stuartd

Programmer
Jan 8, 2001
146
US
I think that I am having problems with the scope of variables. (Using GNU C++ on Solaris)

Let me summarise the code :

main()
{
char *ptr;
my_cls *problem;

ptr=func();

problem=new my_cls;

printf("--%s--",ptr);
}

char *func()
{
string temp;
char *returnptr;

temp="Hello";
temp=temp+" World";

returnptr=temp.c_str(); // Returns char* from string

return(returnptr);
}

This simple example shows what I am doing - a function returns a pointer to char.
When the processing returns to the calling main() function, the pointer 'ptr' is not pointing to anything, as the 'temp' which was local to func() has been deleted and the memory freed (I am assuming).

Someone must have seen this happen before? Is there a simple cure to this problem?
 
the quick fix but not the appropriate is to make temp static. If you are not doing multi-threaded stuff, it should be fine.

Matt
 
I think you may may want to allocate memmory to store temp variable... something like that:

char *func()
{
string temp;
char *returnptr;

temp="Hello";
temp=temp+" World";

returnptr = new char[ temp.length() + 1];

strcpy( returnptr, temp.c_str() );

return(returnptr);
}

....and don't forget to delete ptr to avoid memory leaks...

Cheers,
BatVanko ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top