Search code examples
c++stringdlopen

Wrong string library after dlopen?


im currently using dlopen on a modular program and I think something is really wrong, but I cant seem to figure it out.

requirementData is a vector of a class called VoidData. It's simply a class to handle void* easily

getCopyOfData() uses memcpy to copy the data stored in the void*. Until here everthing is fine, the address of voidptr is different from the one stored in my VoidData object so the copy was a success.

Now... stringA gives me the right string. This is also okay for stringB. But then comes stringC and he gives me something weird.

void* voidptr = requirementData[0].getCopyOfData();

string stringA = *((string*) voidptr);
cout << "VoidPtr: " << stringA << endl; // VoidPtr: 'SayHey'

string stringB = *((string*) voidptr);
cout << "VoidPtr: " << stringB << endl; // VoidPtr: 'SayHey'

// load library
void *handle = dlopen("/usr/lib64/libOpcWorkingPackage.so", RTLD_LAZY);

string stringC = *((string*) voidptr);
cout << "VoidPtr: " << stringC << endl; // VoidPtr: '����'

I also tried to cast voidptr to an array of uint8_t. Every time the array gives me the same 32 numbers.

for (unsigned int i = 0; i < sizeof(stringC); i++){
    cout << to_string(((uint8_t*) voidptr)[i]) << ", ";
}
cout << endl;
// 80, 181, 228, 245, 255, 127, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 83, 97, 121, 101, 119, 121, 0, 0, 0, 183, 228, 245, 255, 127, 49, 52

Im out of ideas, maybe somebody can help me.

Thanks, Narase

Edit: Here's my getCopyOfData() function:

void* VoidData::getCopyOfData() const {
    void *data = malloc(size);
    memcpy(data, storedData, size);
    return data;
}

Edit: Got it

The data I get are a char[]. This char[] is put in a string which doesnt copy them, it just puts a pointer on it. After the char[] is released, the string works until the memory issnt used anymore after that

Thank you for the correct idea user4581301!


Solution

  • The data I get is in a char[]. This char[] is put in a string (by me) which doesnt copy them, it just puts a pointer on it. After the char[] is released, the string works until the memory issnt used anymore after that.

    Thank you for the correct idea user4581301!