Click to See Complete Forum and Search --> : Returning a string


Scribe
May 8th, 2005, 09:39 AM
A bit of a trivial question i know, but i was wrapping up the libmcrypt for a particular project of mine.

to encrypt data, i pass the text that needs encrypting, because it's being read from a socket, then parsed, i don't always know the length of the string, so i declare it as 'char *pString;'

However, if i pass this to the encryption function and the text contained is over 16chars long, my program crashes. I'm guessing this is due to some way the encryption method works, the 16limit being the block size of the method i'm using.

I found a work-around, which is to strlen() the text that needs encrypting, and placing it in a correctly sized string and so that it is a multiple of 16. like this:


short int Length = strlen( To_Be_Encrypted );

short int Temp_Length;

if( (Temp_Length = Length % 16) != 0 )
{
Length = Length + ( 16 - Temp_Length );
}

char Temp_To_Be_Encrypted[Length];


The encryption function then encrypts the text and returns the encrypted data in the same array as i gave it.

This issue is that this function (from my wrapping) must then return the array, however, to return it as a pointer wont work because the function will close and erase the data it's pointing to. I can't work out how to pass actual physical string data from the function. It would be inconvenient to declare the new data on the heap as i would have to remember to delete it when i'm done.

Can anyone think of a better workaround / way to return my encrypted string?

Thanks.

NoHero
May 8th, 2005, 10:55 AM
Then use either std::string to handle string (notice: strings from a network socket are normally not null terminated.) or use dynamic allocation for your array by either using malloc() or new. And return this pointer to the user. But notice: The calling procedure must clean up the pointer you allocate. So I think the std::string solution is the best.

std::string encrypt ( const std::string& toencrypt )
{
std::string temp;

// encrypt here

return temp;
}