Archived Forum Post

Index of archived forum posts

Question:

CkSFtp::openDir() fails at its 11th usage

Aug 11 '16 at 06:18

Hi

The CkSFtp::openDir() (C++ library, 9.5.0-x86-vc9) when using it for more than 10 times.
Using it as in the example, it works correctly for the first 10 usage, with readDir() and Closehandle() working correctly as well.
The simplest code below also fails at 10th iteration:
// After successful connect and authenticate
for (int i = 0; i < 20; i++)
{
const char* hDir = sftp.openDir(".");
sftp.CloseHandle(hDir);
}

Tried with various SSH/SFTP servers, and the behaviour is the same.

As another question, when using CkSFtp::OpenDir(), which returns a bool and a CkString as output parameter, what handle should be used in CkSFtp::CloseHandle()?

Thanks


Accepted Answer

Problem found, in my code.
Previous to the example code above there was the code segment below:
const char *absPath = sftp.realPath(".","");
//save absolute path
delete absPath;
As it turned out, the "delete" is not needed, most probably it uses the same internal pool of buffers as openDir(), which was destroyed, but the same pointer was reused in openDir().


Answer

See this: http://cknotes.com/chilkat-c-api-lowercase-methods-returning-const-char/

I tested your simplest code, and everything works perfectly.

The reason the 11th try would fail is because there are 10 internal pointers that are recycled for the lowercase method calls.

For example:

const char ptr1 = chilkatObject.lowerCaseMethodReturningString(xyz);
const char ptr2 = chilkatObject.lowerCaseMethodReturningString(xyz);
const char ptr3 = chilkatObject.lowerCaseMethodReturningString(xyz);
const char ptr4 = chilkatObject.lowerCaseMethodReturningString(xyz);
...
const char ptr10 = chilkatObject.lowerCaseMethodReturningString(xyz);
// After the next call, ptr1 is no longer valid!
const char ptr11 = chilkatObject.lowerCaseMethodReturningString(xyz);

As described on the web page at the link above:

Important: The lowercase alternative that returns a “const char ” is returning a pointer to internal memory that is not permanent. Your application should make use of it immediately and then discard the pointer. If the string is needed for a longer amount of time, then it should be copied to memory owned and controlled by the application, or the upper-case alternative using CkString should be used instead. If an application keeps a “const char ” pointer and continues to make additional calls on the same Chilkat object instance, the memory pointed to by the “const char *” could change.