Assign pair of raw pointers returned by a function to unique_ptr - pointers

I've looked around a little bit but couldn't find an answer to this.
I have a function returning a pair of pointers to objects, the situation can be simplified to:
#include <iostream>
#include <utility>
#include <memory>
std::pair<int *, int *> shallow_copy()
{
int *i = new int;
int *j = new int;
*i = 5;
*j = 7;
return std::make_pair(i, j);
}
int main(int argc, char *argv[])
{
std::pair<int *, int *> my_pair = shallow_copy();
std::cout << "a = " << my_pair.first << " b = " << *my_pair.second << std::endl;
// This is just creating a newpointer:
std::unique_ptr<int> up(my_pair.first);
std::cout << "a = " << &up << std::endl;
delete my_pair.first;
delete my_pair.second;
return 0;
}
I cannot change the return value of the function. From std::cout << "a = " << &up << std::endl; I can see that the address of the smart pointer is different from the address of the raw pointer.
Is there a way to capture tha std::pair returned by the function in a std::unique_ptr and prevent memory leaks without calling delete explicitly?
NB: The question have been edited to better state the problem and make me look smarter!

You're doing it the right way, but testing it the wrong one. You're comparing the address in first with the address of up. If you print up.get() instead (the address stored in up), you'll find they're equal.
In addition, your code has a double-delete problem. You do delete my_pair.first;, which deallocates the memory block pointed to by my_pair.first and also by up. Then, the destructor of up will deallocate it again when up goes out of scope, resulting in a double delete.
You also asked how to capture both pointers in smart pointers. Since the constructor of std::unique_ptr taking a raw pointer is explicit, you cannot directly do this with a simple std::pair<std::unique_ptr<int>, std::unique_ptr<int>>. You can use a helper function, though:
std::pair<std::unique_ptr<int>, std::unique_ptr<int>> wrapped_shallow_copy()
{
auto orig = shallow_copy();
std::pair<std::unique_ptr<int>, std::unique_ptr<int>> result;
result.first.reset(orig.first);
result.second.reset(orig.second);
return result;
}
Now, use wrapped_shallow_copy() instead of shallow_copy() and you will never leak memory from the call.

Related

Pass a string from ECL to C++

I'm trying to get into the fascinating world of Common Lisp embedded in C++. My problem is that I can't manage to read and print from c++ a string returned by a lisp function defined in ECL.
In C++ I have this function to run arbitrary Lisp expressions:
cl_object lisp(const std::string & call) {
return cl_safe_eval(c_string_to_object(call.c_str()), Cnil, Cnil);
}
I can do it with a number in this way:
ECL:
(defun return-a-number () 5.2)
read and print in C++:
auto x = ecl_to_float(lisp("(return-a-number)"));
std::cout << "The number is " << x << std::endl;
Everything is set and works fine, but I don't know to do it with a string instead of a number. This is what I have tried:
ECL:
(defun return-a-string () "Hello")
C++:
cl_object y = lisp("(return-a-string)");
std::cout << "A string: " << y << std::endl;
And the result of printing the string is this:
A string: 0x3188b00
that I guess is the address of the string.
Here it is a capture of the debugger and the contents of the y cl_object. y->string.self type is an ecl_character.
Debug
(Starting from #coredump's answer that the string.self field provides the result.)
The string.self field is defined as type ecl_character* (ecl/object.h), which appears to be given in ecl/config.h as type int (although I suspect this is slightly platform dependent). Therefore, you will not be able to just print it as if it was a character array.
The way I found worked for me was to reinterpret it as a wchar_t (i.e. a unicode character). Unfortunately, I'm reasonably sure this isn't portable and depends both on how ecl is configured and the C++ compiler.
// basic check that this should work
static_assert(sizeof(ecl_character)==sizeof(wchar_t),"sizes must be the same");
std::wcout << "A string: " << reinterpret_cast<wchar_t*>(y->string.self) << std::endl;
// prints hello, as required
// note the use of wcout
The alternative is to use the lisp type base-string which does use char (base-char in lisp) as its character type. The lisp code then reads
(defun return-a-base-string ()
(coerce "Hello" 'base-string))
(there may be more elegant ways to do the conversion to base-string but I don't know them).
To print in C++
cl_object y2 = lisp("(return-a-base-string)");
std::cout << "Another: " << y2->base_string.self << std::endl;
(note that you can't mix wcout and cout in the same program)
According to section 2.6 Strings of The ECL Manual, I think that the actual character array is found by accessing the string.self field of the returned object. Can you try the following?
std::cout << y->string.self << std::endl;
std::string str {""};
cl_object y2 = lisp("(return-a-base-string)");
//get dimension
int j = y2->string.dim;
//get pointer
ecl_character* selv = y2->string.self;
//do simple pointer addition
for(int i=0;i<j;i++){
str += (*(selv+i));
}
//do whatever you want to str
this code works when the string is build from ecl_characters
from the documentation:
"ECL defines two C types to hold its characters: ecl_base_char and ecl_character.
When ECL is built without Unicode, they both coincide and typically match unsigned char, to cover the 256 codes that are needed.
When ECL is built with Unicode, the two types are no longer equivalent, with ecl_character being larger.
For your code to be portable and future proof, use both types to really express what you intend to do."
On my system the return-a-base-string is not needed, but I think it could be good to add for compatibility. I use the (ecl) embedded CLISP 16.1.2 version.
The following piece of code reads a string from lisp and converts to C++ strings types - std::string and c-string- and store them on C++ variables:
// strings initializations: string and c-string
std::string str2 {""};
char str_c[99] = " ";
// text read from clisp, whatever clisp function that returns string type
cl_object cl_text = lisp("(coerce (text-from-lisp X) 'base-string)");
//cl_object cl_text = lisp("(text-from-lisp X)"); // no base string conversions
// catch dimension
int cl_text_dim = cl_text->string.dim;
// complete c-string char by char
for(int ind=0;i<cl_text_dim;i++){
str_c[i] = ecl_char(cl_text,i); // ecl function to get char from cl_object
}
str_c[cl_text_dim] ='\0'; // end of the c-string
str2 = str_c; // get the string on the other string type
std::cout << "Dim: " << cl_ text_dim << " C-String var: " << str_c() << " String var << str2 << std::endl;
It is a slow process as passing char by char but it is the only way by the moment I know. Hope it helps. Greetings!

C++: OpenSSL, aes cfb encryption [duplicate]

I tried to implement a "very" simple encryption/decryption example. I need it for a project where I would like to encrypt some user information. I can't encrypt the whole database but only some fields in a table.
The database and most of the rest of the project works, except the encryption:
Here is a simplified version of it:
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
/* ckey and ivec are the two 128-bits keys necessary to
en- and recrypt your data. Note that ckey can be
192 or 256 bits as well
*/
unsigned char ckey[] = "helloworldkey";
unsigned char ivec[] = "goodbyworldkey";
int bytes_read;
unsigned char indata[AES_BLOCK_SIZE];
unsigned char outdata[AES_BLOCK_SIZE];
unsigned char decryptdata[AES_BLOCK_SIZE];
/* data structure that contains the key itself */
AES_KEY keyEn;
/* set the encryption key */
AES_set_encrypt_key(ckey, 128, &keyEn);
/* set where on the 128 bit encrypted block to begin encryption*/
int num = 0;
strcpy( (char*)indata , "Hello World" );
bytes_read = sizeof(indata);
AES_cfb128_encrypt(indata, outdata, bytes_read, &keyEn, ivec, &num, AES_ENCRYPT);
cout << "original data:\t" << indata << endl;
cout << "encrypted data:\t" << outdata << endl;
AES_cfb128_encrypt(outdata, decryptdata, bytes_read, &keyEn, ivec, &num, AES_DECRYPT);
cout << "input data was:\t" << decryptdata << endl;
return 0;
}
But the output of "decrypted" data are some random characters, but they are the same after every execution of the code. outdata changes with every execution...
I tried to debug and search for a solution, but I couldn't find any solution for my problem.
Now my question, what is going wrong here? Or do I completely misunderstand the provided functions?
The problem is that AES_cfb128_encrypt modifies the ivec (it has to in order to allow for chaining). Your solution is to create a copy of the ivec and initialize it before each call to AES_cfb128_encrypt as follows:
const char ivecstr[AES_BLOCK_SIZE] = "goodbyworldkey\0";
unsigned char ivec[AES_BLOCK_SIZE];
memcpy( ivec , ivecstr, AES_BLOCK_SIZE);
Then repeat the memcpy before your second call to AES_cfb128_encrypt.
Note 1: Your initial vector was a byte too short, so I put an explicit additional \0 at the end of it. You should make sure all of your strings are of the correct length when copying or passing them.
Note 2: Any code which uses encryption should REALLY avoid using strcpy or any other copy of unchecked length. It's a hazard.

Reading more than one value into variables using QInputDialog

I have to write a small QT program that reads in 3 mark percentages separated by commas and then do some further calculations on the marks... I have to use QInputDialog to do this but it seems like it's only possible to read in one value at a time.
at this stage I am only trying to read in and display the three marks.
When I run this code QTCreator stops working and I have to end the process in task manager.
Any idea how I can approach this would be much appreciated. Should I read in a string and then convert that to double values or is there a simpler way?
Thanks in advance.
Code:
#include <QTGui>
#include <QApplication>
#include <QString>
#include <QTextStream>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTextStream cin(stdin, QIODevice::ReadOnly);
QTextStream cout(stdout, QIODevice::WriteOnly);
double mark1, mark2, mark3;
double passMarkNeeded = 0;
QInputDialog::getDouble(0, "Enter marks", "Marks", 1);
cin >> mark1 >> mark2 >> mark3;
cout << "User entered " << mark1 << mark2 << mark3;
return EXIT_SUCCESS;
}
Obviously you cannot use QInputDialog::getDouble because it won't allow you to input 3 values separated by commas. You should use QInputDialog::getText, QString::split and QString::toDouble:
QStringList list = QInputDialog::getText(0, "Input values", "Input values:").split(",");
if (list.count() == 3) {
double a = list[0].toDouble(),
b = list[1].toDouble(),
c = list[2].toDouble();
qDebug() << "Values:" << a << b << c;
}
I'm not sure why you use QInputDialog and the standard input (cin). QInputDialog is for GUI apps, and cin is console apps. It's strange and pointless to use them together in such a way.

Removing from a std::list with objects

I was taught always to use a pointer list when storing objects, but I started using lists with objects in them instead. So I'm wondering how do I properly remove an object from a list?
The first code example removes from a pointer list and works all right, but the second one gives an error when running. Do I need to use delete when working with list with objects?
using namespace std;
struct SomeObject{
SomeObject(int i){
something=i;
}
int something;
};
void main(){
list<SomeObject*> pointerList;
SomeObject * op = new SomeObject(2);
pointerList.push_back(op);
auto pit = pointerList.begin();
pointerList.erase(pit);
delete *pit;
cout<<(**pit).something<<endl;
list<SomeObject> objectList;
SomeObject o(1);
objectList.push_back(o);
auto oit = objectList.begin();
objectList.erase(oit);
delete &oit;//this one
cout<<oit->something<<endl;
int i;
cin >> i;
}
Also what are down and upsides with doing it this way?
You get the error because oit is an iterator, not a pointer. You use delete on pointers acquired with new. Iterators look like pointers, but they are not pointers. In the example you gave it's just wrong to use delete.
I think it would be more idiomatic (and correct!) this way:
list<SomeObject*> pointerList;
SomeObject * op = new SomeObject(2);
pointerList.push_back(op);
auto pit = pointerList.front();
pointerList.pop_front();
// delete *pit; // wrong
cout << (**pit).something << endl;
list<SomeObject> objectList;
SomeObject o(1);
objectList.push_back(o);
auto oit = objectList.front();
objectList.pop_front();
// delete &oit; // wrong
cout << oit->something << endl;

Does QT's QList save iterators after container's modifications?

Are the iterators pointed to elements of QList still valid after there are any remove operation from QList?
I need to remove some element from QList, so I store an iterators for those elements to another container and than take this saved iterators and use to remove necessary elements from QList.
It looks like this:
// inside a loop for 'list'
QList<type>::iterator it = list.begin() + j;
removing.append(it);
// end of loop for 'list'
...
while(removing.empty() == false)
{
list.erase(removing.takeFirst());
}
So, when removing container contains more than 1 element, app crash occurs (SEGMENTATION FAULT) when attempting to erase second element, whereas first was erased successfully.
What is the reason and is there any way to remove elements with iterators?
If for some reason you would like to remove elements from a container in that way then you could try to use QLinkedList instead of QList because Iterators pointing to an item in a QLinkedList remain valid as long as the item exists, whereas iterators to a QList can become invalid after any insertion or removal. I copied this quotation from Qt's documentation: Container Classes.
No, the iterators will not be valid. If you just want to remove all the elements, use QList::clear(). You can call qDeleteAll() on the QList first if you need to delete the items.
If you want to selectively remove elements using iterators, you can do something like the following. You may need to modify it for memory management.
#include <QtCore>
#include <QtDebug>
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
QList<int> items;
items << 0 << 1 << 1 << 2 << 3 << 5 << 8 << 13 << 21 << 34 << 55 << 89 << 144;
QList<int>::iterator i = items.begin();
while (i != items.end()) {
if ((*i) % 2 == 0) {
// i->DoSomething(); // Not with ints, obviously, but in general.
i = items.erase(i); // i points to the next item.
} else {
++i;
}
}
qDebug() << items;
return app.exec();
}

Resources