Click to See Complete Forum and Search --> : [RESOLVED] Char * Function() return problem
vc185002
January 22nd, 2007, 07:31 AM
what could be wrong with the code?
i want some thing on local variable assinged a local pointer which is returned. The values are received correctly. But is it wrong practice or not? & what is a better way to do it.
char ptr* GetSomething()
{
char buff[100] ;
strcpy( buff, "C++") ;
char *pLocalPtr ;
pLocalPtr = buff ;
return pLocalPtr ;
}
int main()
{
char *ptr = GetSomething() ;
printf( "i got -- > %s", ptr );
}
screetch
January 22nd, 2007, 07:47 AM
the values are not received correctly. It works by luck or because you didn't enable all the debug options
under Visual C++ 2005 in Release mode the code seems to work fine but in Debug it prints garbage on the screen.
You are returning a pointer that addresses memory on the stack (the buff variable), so as soon as the function returns the memory can be erased
It seems to work because the memory has not been replaced by something else yet, but as soon as you call another function the local variables will take the place of your buffer
If you want to return a value, don't return a temporary, return a copy. If you want to get rid of these problems return a string object that encapsulates the char* pointer, it will handle this case.
GNiewerth
January 22nd, 2007, 07:58 AM
Hi,
fist IŽd recommend the use of std::vector instead of char *. Then you can pass a reference of that vector to your function and fill in data:
void GetSomething( std::vector<char>& Data )
{
std::string SomeData = "C++";
// reserve space
Data.reserve( Data.length() +1 );
// copy data
std::copy( SomeData.begin(), SomeData.end(), back_inserter( Data ) );
}
int main()
{
std::vector<char> Data;
// get data
GetSomeThing( Data );
// pointer to first data byte
char *pszReturnString = &Data[0];
}
If you want to pass binary data you have to specify the start and end address of the memory range to copy:
void GetSomething( std::vector<char>& Data )
{
char *pcSomeMemoryBlock;
int iDataLength;
// reserve space
Data.reserve( iDataLength );
// copy data
std::copy( pcMemoryBlock, pcMemoryBlock + iDataLength, back_inserter( Data ) );
}
Hope this helps,
Guido
vc185002
January 22nd, 2007, 08:02 AM
std::string GetSomething()
{
std::string buff="p";
return buff ;
}
int main()
{
std::string ptrr = GetSomething() ;
}
& is this d correct way?
btw.. first one fails........;D
screetch
January 22nd, 2007, 08:06 AM
Yep, this is correct. The local variable is copied to be returned and you don't keep a eference (or a pointer) on the stack of the function after it has returned
vc185002
January 22nd, 2007, 08:16 AM
thanks friends for giving ur suggestions...............thread resolved...
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.